| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const fs = require('fs'); |
| 5 | const http = require('http'); |
| 6 | const os = require('os'); |
| 7 | const path = require('path'); |
| 8 | const { once } = require('events'); |
| 9 | |
| 10 | let mockPaths = []; |
| 11 | let mockRootAliases = {}; |
| 12 | let mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 13 | let mockThumbPath = null; |
| 14 | let mockFolderImages = []; |
| 15 | let mockFolderIconFile = null; |
| 16 | let lastFolderIconAssignment = undefined; |
| 17 | let mockVideoStreamSession = null; |
| 18 | let mockVideoStreamAsset = null; |
| 19 | let releasedVideoStreamSessionId = null; |
| 20 | |
| 21 | jest.mock('../server/db', () => |
| 22 | { |
| 23 | const { Database } = require('node-sqlite3-wasm'); |
| 24 | let db; |
| 25 | function getDb () |
| 26 | { |
| 27 | if (!db) |
| 28 | { |
| 29 | db = new Database(':memory:'); |
| 30 | db.exec(` |
| 31 | CREATE TABLE IF NOT EXISTS users ( |
| 32 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 33 | username TEXT UNIQUE NOT NULL, |
| 34 | password_hash TEXT NOT NULL, |
| 35 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 36 | permissions TEXT NOT NULL DEFAULT '{}' |
| 37 | ); |
| 38 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 39 | file_path TEXT PRIMARY KEY, |
| 40 | uploader TEXT NOT NULL DEFAULT '', |
| 41 | downloaders TEXT NOT NULL DEFAULT '[]', |
| 42 | watched_by TEXT NOT NULL DEFAULT '{}', |
| 43 | sha256 TEXT |
| 44 | ); |
| 45 | CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256); |
| 46 | `); |
| 47 | } |
| 48 | return db; |
| 49 | } |
| 50 | return { getDb, initDb: getDb }; |
| 51 | }); |
| 52 | |
| 53 | jest.mock('../server/config', () => ({ |
| 54 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }), |
| 55 | saveConfig: (config) => |
| 56 | { |
| 57 | mockPaths = [...(config.paths || [])]; |
| 58 | mockRootAliases = { ...(config.rootAliases || {}) }; |
| 59 | }, |
| 60 | getEffectivePaths: (paths) => paths, |
| 61 | getAllowedRoot: (targetPath, roots) => |
| 62 | { |
| 63 | const path = require('path'); |
| 64 | const absTarget = path.resolve(String(targetPath || '')); |
| 65 | return roots.find((root) => |
| 66 | { |
| 67 | const absRoot = path.resolve(root); |
| 68 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 69 | }) || null; |
| 70 | }, |
| 71 | })); |
| 72 | |
| 73 | jest.mock('../server/auth', () => ({ |
| 74 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 75 | })); |
| 76 | |
| 77 | jest.mock('../server/thumbnail-cache', () => ({ |
| 78 | getCachedThumbnailInfo: async () => |
| 79 | { |
| 80 | if (!mockThumbPath) return null; |
| 81 | return { thumbPath: mockThumbPath, contentType: 'image/webp' }; |
| 82 | }, |
| 83 | getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(), |
| 84 | getFolderIconSourceFile: async () => mockFolderIconFile, |
| 85 | setFolderIconAssignment: async (folderPath, imagePath) => |
| 86 | { |
| 87 | lastFolderIconAssignment = { folderPath, imagePath }; |
| 88 | }, |
| 89 | })); |
| 90 | |
| 91 | jest.mock('../server/video-stream', () => ({ |
| 92 | createVideoStreamSession: jest.fn(async () => |
| 93 | { |
| 94 | if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; |
| 95 | return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] }; |
| 96 | }), |
| 97 | sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) => |
| 98 | { |
| 99 | if (typeof mockVideoStreamAsset === 'function') |
| 100 | { |
| 101 | await mockVideoStreamAsset(sessionId, assetPath, req, res); |
| 102 | return; |
| 103 | } |
| 104 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 105 | }), |
| 106 | releaseVideoStreamSession: jest.fn((sessionId) => |
| 107 | { |
| 108 | releasedVideoStreamSessionId = String(sessionId || ''); |
| 109 | return true; |
| 110 | }), |
| 111 | })); |
| 112 | |
| 113 | const filesRoutes = require('../server/routes/files'); |
| 114 | const { getDb } = require('../server/db'); |
| 115 | |
| 116 | let server; |
| 117 | let baseUrl; |
| 118 | let rootDir; |
| 119 | |
| 120 | beforeAll(async () => |
| 121 | { |
| 122 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 123 | mockPaths = [rootDir]; |
| 124 | |
| 125 | const app = express(); |
| 126 | app.use(express.json()); |
| 127 | app.use('/api/files', filesRoutes); |
| 128 | app.use((err, req, res, next) => |
| 129 | { |
| 130 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 131 | }); |
| 132 | |
| 133 | server = http.createServer(app); |
| 134 | server.listen(0); |
| 135 | await once(server, 'listening'); |
| 136 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 137 | }); |
| 138 | |
| 139 | afterAll(() => |
| 140 | { |
| 141 | server.close(); |
| 142 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 143 | }); |
| 144 | |
| 145 | beforeEach(() => |
| 146 | { |
| 147 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 148 | fs.mkdirSync(rootDir, { recursive: true }); |
| 149 | mockRootAliases = {}; |
| 150 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 151 | mockThumbPath = null; |
| 152 | mockFolderImages = []; |
| 153 | mockFolderIconFile = null; |
| 154 | lastFolderIconAssignment = undefined; |
| 155 | mockVideoStreamSession = null; |
| 156 | mockVideoStreamAsset = null; |
| 157 | releasedVideoStreamSessionId = null; |
| 158 | const db = getDb(); |
| 159 | db.prepare('DELETE FROM file_meta').run([]); |
| 160 | db.prepare('DELETE FROM users').run([]); |
| 161 | }); |
| 162 | |
| 163 | function req (method, routePath, body) |
| 164 | { |
| 165 | const payload = body ? JSON.stringify(body) : undefined; |
| 166 | return new Promise((resolve, reject) => |
| 167 | { |
| 168 | const request = http.request(baseUrl + routePath, { |
| 169 | method, |
| 170 | headers: { |
| 171 | 'Content-Type': 'application/json', |
| 172 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 173 | }, |
| 174 | }, res => |
| 175 | { |
| 176 | let data = ''; |
| 177 | res.on('data', chunk => data += chunk); |
| 178 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 179 | }); |
| 180 | request.on('error', reject); |
| 181 | if (payload) request.write(payload); |
| 182 | request.end(); |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | function reqRaw (method, routePath) |
| 187 | { |
| 188 | return new Promise((resolve, reject) => |
| 189 | { |
| 190 | const request = http.request(baseUrl + routePath, { method }, res => |
| 191 | { |
| 192 | const chunks = []; |
| 193 | res.on('data', chunk => chunks.push(Buffer.from(chunk))); |
| 194 | res.on('end', () => resolve({ |
| 195 | status: res.statusCode, |
| 196 | headers: res.headers, |
| 197 | body: Buffer.concat(chunks), |
| 198 | })); |
| 199 | }); |
| 200 | request.on('error', reject); |
| 201 | request.end(); |
| 202 | }); |
| 203 | } |
| 204 | |
| 205 | function reqMultipart (routePath, files, extraHeaders = {}) |
| 206 | { |
| 207 | const boundary = '----filemanager-test-boundary'; |
| 208 | const buffers = []; |
| 209 | |
| 210 | for (const file of files) |
| 211 | { |
| 212 | buffers.push(Buffer.from( |
| 213 | `--${boundary}\r\n` |
| 214 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 215 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 216 | )); |
| 217 | buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content))); |
| 218 | buffers.push(Buffer.from('\r\n')); |
| 219 | } |
| 220 | |
| 221 | buffers.push(Buffer.from(`--${boundary}--\r\n`)); |
| 222 | const payload = Buffer.concat(buffers); |
| 223 | |
| 224 | return new Promise((resolve, reject) => |
| 225 | { |
| 226 | const request = http.request(baseUrl + routePath, { |
| 227 | method: 'POST', |
| 228 | headers: { |
| 229 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 230 | 'Content-Length': payload.length, |
| 231 | ...extraHeaders, |
| 232 | }, |
| 233 | }, res => |
| 234 | { |
| 235 | let data = ''; |
| 236 | res.on('data', chunk => data += chunk); |
| 237 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 238 | }); |
| 239 | request.on('error', reject); |
| 240 | request.write(payload); |
| 241 | request.end(); |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | function abortMultipartUpload (routePath, file) |
| 246 | { |
| 247 | const boundary = '----filemanager-test-boundary-abort'; |
| 248 | const header = Buffer.from( |
| 249 | `--${boundary}\r\n` |
| 250 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 251 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 252 | ); |
| 253 | const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)); |
| 254 | |
| 255 | return new Promise((resolve) => |
| 256 | { |
| 257 | const request = http.request(baseUrl + routePath, { |
| 258 | method: 'POST', |
| 259 | headers: { |
| 260 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 261 | }, |
| 262 | }); |
| 263 | |
| 264 | let settled = false; |
| 265 | const finish = () => |
| 266 | { |
| 267 | if (settled) return; |
| 268 | settled = true; |
| 269 | resolve(); |
| 270 | }; |
| 271 | |
| 272 | request.on('error', finish); |
| 273 | request.on('close', finish); |
| 274 | request.write(header); |
| 275 | request.write(chunk); |
| 276 | setTimeout(() => request.destroy(), 20); |
| 277 | }); |
| 278 | } |
| 279 | |
| 280 | async function waitFor(predicate, timeoutMs = 500) |
| 281 | { |
| 282 | const start = Date.now(); |
| 283 | while (Date.now() - start < timeoutMs) |
| 284 | { |
| 285 | if (predicate()) return; |
| 286 | await new Promise(resolve => setTimeout(resolve, 10)); |
| 287 | } |
| 288 | throw new Error('Timed out waiting for condition.'); |
| 289 | } |
| 290 | |
| 291 | describe('POST /api/files/upload', () => |
| 292 | { |
| 293 | test('stores a completed upload under its final name', async () => |
| 294 | { |
| 295 | const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 296 | { name: 'hello.txt', content: 'hello world', type: 'text/plain' }, |
| 297 | ]); |
| 298 | |
| 299 | expect(status).toBe(200); |
| 300 | expect(body.uploaded).toEqual(['hello.txt']); |
| 301 | expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world'); |
| 302 | |
| 303 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 304 | .get([path.join(rootDir, 'hello.txt')]); |
| 305 | expect(meta).toMatchObject({ uploader: 'admin' }); |
| 306 | }); |
| 307 | |
| 308 | test('removes partial files when the upload connection aborts', async () => |
| 309 | { |
| 310 | await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, { |
| 311 | name: 'partial.txt', |
| 312 | content: Buffer.alloc(256 * 1024, 'a'), |
| 313 | type: 'text/plain', |
| 314 | }); |
| 315 | |
| 316 | await waitFor(() => fs.readdirSync(rootDir).length === 0); |
| 317 | |
| 318 | expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false); |
| 319 | expect(fs.readdirSync(rootDir)).toEqual([]); |
| 320 | |
| 321 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 322 | .get([path.join(rootDir, 'partial.txt')]); |
| 323 | expect(meta).toBeFalsy(); |
| 324 | }); |
| 325 | }); |
| 326 | |
| 327 | describe('POST /api/files/move', () => |
| 328 | { |
| 329 | test('moves a file into another folder and rewrites metadata', async () => |
| 330 | { |
| 331 | const from = path.join(rootDir, 'alpha.txt'); |
| 332 | const toDir = path.join(rootDir, 'folder'); |
| 333 | fs.writeFileSync(from, 'hello'); |
| 334 | fs.mkdirSync(toDir); |
| 335 | |
| 336 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 337 | .run([from, 'admin', '["alice"]']); |
| 338 | |
| 339 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 340 | |
| 341 | expect(status).toBe(200); |
| 342 | expect(body.ok).toBe(true); |
| 343 | expect(fs.existsSync(from)).toBe(false); |
| 344 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 345 | |
| 346 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 347 | expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); |
| 348 | }); |
| 349 | |
| 350 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 351 | { |
| 352 | const fromDir = path.join(rootDir, 'src-folder'); |
| 353 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 354 | const toDir = path.join(rootDir, 'dest-folder'); |
| 355 | fs.mkdirSync(fromDir); |
| 356 | fs.mkdirSync(toDir); |
| 357 | fs.writeFileSync(nestedFile, 'hello'); |
| 358 | |
| 359 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 360 | .run([nestedFile, 'admin', '[]']); |
| 361 | |
| 362 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 363 | |
| 364 | expect(status).toBe(200); |
| 365 | expect(fs.existsSync(fromDir)).toBe(false); |
| 366 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 367 | |
| 368 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 369 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 370 | expect(movedMeta).toBeTruthy(); |
| 371 | }); |
| 372 | |
| 373 | test('rejects moving a folder into itself', async () => |
| 374 | { |
| 375 | const fromDir = path.join(rootDir, 'src-folder'); |
| 376 | const childDir = path.join(fromDir, 'child'); |
| 377 | fs.mkdirSync(childDir, { recursive: true }); |
| 378 | |
| 379 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 380 | |
| 381 | expect(status).toBe(400); |
| 382 | expect(body.error).toMatch(/folder into itself/i); |
| 383 | }); |
| 384 | |
| 385 | test('overwrites an existing destination when conflict strategy is overwrite', async () => |
| 386 | { |
| 387 | const sourceFile = path.join(rootDir, 'source.txt'); |
| 388 | const destinationDir = path.join(rootDir, 'dest'); |
| 389 | fs.mkdirSync(destinationDir); |
| 390 | fs.writeFileSync(sourceFile, 'new-content'); |
| 391 | fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content'); |
| 392 | |
| 393 | const { status, body } = await req('POST', '/api/files/move', { |
| 394 | from: sourceFile, |
| 395 | toDir: destinationDir, |
| 396 | conflict: 'overwrite', |
| 397 | }); |
| 398 | |
| 399 | expect(status).toBe(200); |
| 400 | expect(body.conflictResolution).toBe('overwrite'); |
| 401 | expect(fs.existsSync(sourceFile)).toBe(false); |
| 402 | expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content'); |
| 403 | }); |
| 404 | |
| 405 | test('renames destination when conflict strategy is rename', async () => |
| 406 | { |
| 407 | const sourceFile = path.join(rootDir, 'report.txt'); |
| 408 | const destinationDir = path.join(rootDir, 'dest'); |
| 409 | fs.mkdirSync(destinationDir); |
| 410 | fs.writeFileSync(sourceFile, 'latest'); |
| 411 | fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing'); |
| 412 | |
| 413 | const { status, body } = await req('POST', '/api/files/move', { |
| 414 | from: sourceFile, |
| 415 | toDir: destinationDir, |
| 416 | conflict: 'rename', |
| 417 | }); |
| 418 | |
| 419 | expect(status).toBe(200); |
| 420 | expect(body.conflictResolution).toBe('rename'); |
| 421 | expect(path.basename(body.path)).toBe('report (1).txt'); |
| 422 | expect(fs.readFileSync(body.path, 'utf8')).toBe('latest'); |
| 423 | expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing'); |
| 424 | }); |
| 425 | }); |
| 426 | |
| 427 | describe('root alias endpoints', () => |
| 428 | { |
| 429 | test('GET /api/files/roots returns alias label and original name', async () => |
| 430 | { |
| 431 | mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; |
| 432 | |
| 433 | const { status, body } = await req('GET', '/api/files/roots'); |
| 434 | |
| 435 | expect(status).toBe(200); |
| 436 | expect(body.roots).toHaveLength(1); |
| 437 | expect(body.roots[0]).toMatchObject({ |
| 438 | path: rootDir, |
| 439 | label: 'Workspace', |
| 440 | alias: 'Workspace', |
| 441 | originalName: path.basename(rootDir), |
| 442 | }); |
| 443 | }); |
| 444 | |
| 445 | test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => |
| 446 | { |
| 447 | const originalBase = path.basename(rootDir); |
| 448 | const { status, body } = await req('POST', '/api/files/root-alias', { |
| 449 | rootPath: rootDir, |
| 450 | alias: 'Shared Files', |
| 451 | }); |
| 452 | |
| 453 | expect(status).toBe(200); |
| 454 | expect(body.ok).toBe(true); |
| 455 | expect(body.root).toMatchObject({ |
| 456 | path: rootDir, |
| 457 | label: 'Shared Files', |
| 458 | alias: 'Shared Files', |
| 459 | originalName: originalBase, |
| 460 | }); |
| 461 | expect(fs.existsSync(rootDir)).toBe(true); |
| 462 | |
| 463 | const afterRoots = await req('GET', '/api/files/roots'); |
| 464 | expect(afterRoots.status).toBe(200); |
| 465 | expect(afterRoots.body.roots[0].label).toBe('Shared Files'); |
| 466 | expect(afterRoots.body.roots[0].originalName).toBe(originalBase); |
| 467 | }); |
| 468 | |
| 469 | test('POST /api/files/root-alias rejects non-root paths', async () => |
| 470 | { |
| 471 | const nested = path.join(rootDir, 'sub'); |
| 472 | fs.mkdirSync(nested, { recursive: true }); |
| 473 | |
| 474 | const { status } = await req('POST', '/api/files/root-alias', { |
| 475 | rootPath: nested, |
| 476 | alias: 'Nested', |
| 477 | }); |
| 478 | |
| 479 | expect(status).toBe(400); |
| 480 | }); |
| 481 | }); |
| 482 | |
| 483 | describe('GET /api/files/thumbnail', () => |
| 484 | { |
| 485 | test('returns 404 while cached thumbnail is not ready', async () => |
| 486 | { |
| 487 | const source = path.join(rootDir, 'photo.jpg'); |
| 488 | fs.writeFileSync(source, 'not-an-image'); |
| 489 | |
| 490 | const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 491 | expect(status).toBe(404); |
| 492 | expect(body.error).toMatch(/not ready/i); |
| 493 | }); |
| 494 | |
| 495 | test('serves cached thumbnail file when available', async () => |
| 496 | { |
| 497 | const source = path.join(rootDir, 'photo.jpg'); |
| 498 | const thumb = path.join(rootDir, 'photo-thumb.webp'); |
| 499 | fs.writeFileSync(source, 'not-an-image'); |
| 500 | fs.writeFileSync(thumb, 'webp-bytes'); |
| 501 | mockThumbPath = thumb; |
| 502 | |
| 503 | const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 504 | expect(response.status).toBe(200); |
| 505 | expect(String(response.headers['content-type'] || '')).toContain('image/webp'); |
| 506 | expect(response.body.toString('utf8')).toBe('webp-bytes'); |
| 507 | }); |
| 508 | }); |
| 509 | |
| 510 | describe('GET /api/files/root-access', () => |
| 511 | { |
| 512 | test('returns users with R/R+W modes for an exact root path', async () => |
| 513 | { |
| 514 | const label = path.basename(rootDir); |
| 515 | const db = getDb(); |
| 516 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 517 | .run(['admin', 'x', 1, '{}']); |
| 518 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 519 | .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]); |
| 520 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 521 | .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]); |
| 522 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 523 | .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]); |
| 524 | |
| 525 | const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`); |
| 526 | expect(status).toBe(200); |
| 527 | expect(body.root).toMatchObject({ path: rootDir, originalName: label }); |
| 528 | expect(body.users).toEqual([ |
| 529 | { username: 'admin', mode: 'R+W' }, |
| 530 | { username: 'bob', mode: 'R+W' }, |
| 531 | { username: 'alice', mode: 'R' }, |
| 532 | ]); |
| 533 | }); |
| 534 | |
| 535 | test('rejects non-exact nested root paths', async () => |
| 536 | { |
| 537 | const nested = path.join(rootDir, 'sub'); |
| 538 | fs.mkdirSync(nested, { recursive: true }); |
| 539 | |
| 540 | const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`); |
| 541 | expect(status).toBe(400); |
| 542 | }); |
| 543 | }); |
| 544 | |
| 545 | describe('folder icon endpoints', () => |
| 546 | { |
| 547 | test('GET /api/files/folder-images returns images that have cached thumbnails', async () => |
| 548 | { |
| 549 | const subDir = path.join(rootDir, 'photos'); |
| 550 | fs.mkdirSync(subDir); |
| 551 | const imgPath = path.join(subDir, 'a.jpg'); |
| 552 | fs.writeFileSync(imgPath, 'img'); |
| 553 | |
| 554 | mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }]; |
| 555 | |
| 556 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 557 | expect(status).toBe(200); |
| 558 | expect(body.images).toHaveLength(1); |
| 559 | expect(body.images[0].filePath).toBe(imgPath); |
| 560 | }); |
| 561 | |
| 562 | test('GET /api/files/folder-images returns empty list when no thumbnails available', async () => |
| 563 | { |
| 564 | mockFolderImages = []; |
| 565 | |
| 566 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 567 | expect(status).toBe(200); |
| 568 | expect(body.images).toEqual([]); |
| 569 | }); |
| 570 | |
| 571 | test('GET /api/files/folder-icon returns null when no icon available', async () => |
| 572 | { |
| 573 | mockFolderIconFile = null; |
| 574 | |
| 575 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 576 | expect(status).toBe(200); |
| 577 | expect(body.icon).toBeNull(); |
| 578 | }); |
| 579 | |
| 580 | test('GET /api/files/folder-icon returns source file path when icon is available', async () => |
| 581 | { |
| 582 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 583 | fs.writeFileSync(imgPath, 'img'); |
| 584 | mockFolderIconFile = imgPath; |
| 585 | |
| 586 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 587 | expect(status).toBe(200); |
| 588 | expect(body.icon).toMatchObject({ filePath: imgPath }); |
| 589 | }); |
| 590 | |
| 591 | test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () => |
| 592 | { |
| 593 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 594 | const thumbFile = path.join(rootDir, 'cover.webp'); |
| 595 | fs.writeFileSync(imgPath, 'img'); |
| 596 | fs.writeFileSync(thumbFile, 'webp'); |
| 597 | mockThumbPath = thumbFile; |
| 598 | |
| 599 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 600 | folderPath: rootDir, |
| 601 | imagePath: imgPath, |
| 602 | }); |
| 603 | expect(status).toBe(200); |
| 604 | expect(body.ok).toBe(true); |
| 605 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath }); |
| 606 | }); |
| 607 | |
| 608 | test('POST /api/files/folder-icon rejects image without cached thumbnail', async () => |
| 609 | { |
| 610 | const imgPath = path.join(rootDir, 'missing.jpg'); |
| 611 | fs.writeFileSync(imgPath, 'img'); |
| 612 | mockThumbPath = null; |
| 613 | |
| 614 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 615 | folderPath: rootDir, |
| 616 | imagePath: imgPath, |
| 617 | }); |
| 618 | expect(status).toBe(404); |
| 619 | expect(body.error).toMatch(/thumbnail not ready/i); |
| 620 | }); |
| 621 | |
| 622 | test('POST /api/files/folder-icon clears assignment when imagePath is null', async () => |
| 623 | { |
| 624 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 625 | folderPath: rootDir, |
| 626 | imagePath: null, |
| 627 | }); |
| 628 | expect(status).toBe(200); |
| 629 | expect(body.ok).toBe(true); |
| 630 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null }); |
| 631 | }); |
| 632 | |
| 633 | test('POST /api/files/folder-icon returns 403 for read-only user', async () => |
| 634 | { |
| 635 | const label = path.basename(rootDir); |
| 636 | mockUser = { |
| 637 | username: 'reader', |
| 638 | isAdmin: false, |
| 639 | permissions: { [label]: { read: true, write: false } }, |
| 640 | }; |
| 641 | |
| 642 | const imgPath = path.join(rootDir, 'photo.jpg'); |
| 643 | fs.writeFileSync(imgPath, 'img'); |
| 644 | |
| 645 | const { status } = await req('POST', '/api/files/folder-icon', { |
| 646 | folderPath: rootDir, |
| 647 | imagePath: imgPath, |
| 648 | }); |
| 649 | expect(status).toBe(403); |
| 650 | }); |
| 651 | }); |
| 652 | |
| 653 | // --------------------------------------------------------------------------- |
| 654 | // GET /api/files/download-zip |
| 655 | // --------------------------------------------------------------------------- |
| 656 | describe('GET /api/files/download-zip', () => |
| 657 | { |
| 658 | beforeEach(() => |
| 659 | { |
| 660 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 661 | }); |
| 662 | |
| 663 | test('streams a valid zip for an accessible directory', async () => |
| 664 | { |
| 665 | const subDir = path.join(rootDir, 'zipme'); |
| 666 | fs.mkdirSync(subDir); |
| 667 | fs.writeFileSync(path.join(subDir, 'file.txt'), 'content'); |
| 668 | |
| 669 | const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`); |
| 670 | expect(status).toBe(200); |
| 671 | |
| 672 | const ct = headers['content-type'] || ''; |
| 673 | expect(ct.includes('zip') || ct.includes('octet')).toBe(true); |
| 674 | |
| 675 | // ZIP magic bytes PK\x03\x04 |
| 676 | expect(buf[0]).toBe(0x50); |
| 677 | expect(buf[1]).toBe(0x4b); |
| 678 | }, 20000); |
| 679 | |
| 680 | test('returns 400 when dir param is missing', async () => |
| 681 | { |
| 682 | const { status } = await req('GET', '/api/files/download-zip'); |
| 683 | expect(status).toBe(400); |
| 684 | }); |
| 685 | |
| 686 | test('returns 404 for a non-existent directory', async () => |
| 687 | { |
| 688 | const missing = path.join(rootDir, 'ghost'); |
| 689 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`); |
| 690 | expect(status).toBe(404); |
| 691 | }); |
| 692 | |
| 693 | test('returns 403 for path outside configured roots', async () => |
| 694 | { |
| 695 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`); |
| 696 | expect(status).toBe(403); |
| 697 | }); |
| 698 | }); |
| 699 | |
| 700 | describe('video streaming routes', () => |
| 701 | { |
| 702 | test('POST /api/files/video-stream creates a short-lived playlist session', async () => |
| 703 | { |
| 704 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 705 | fs.writeFileSync(filePath, 'video'); |
| 706 | mockVideoStreamSession = { |
| 707 | sessionId: 'sess-123', |
| 708 | durationSeconds: 42.25, |
| 709 | subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], |
| 710 | }; |
| 711 | |
| 712 | const { status, body } = await req('POST', '/api/files/video-stream', { filePath }); |
| 713 | |
| 714 | expect(status).toBe(200); |
| 715 | expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8'); |
| 716 | expect(body.durationSeconds).toBe(42.25); |
| 717 | expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 }); |
| 718 | expect(body.subtitleTracks).toEqual([ |
| 719 | { |
| 720 | label: 'English', |
| 721 | language: 'eng', |
| 722 | default: true, |
| 723 | src: '/api/files/video-stream/sess-123/subtitle-0.vtt', |
| 724 | }, |
| 725 | ]); |
| 726 | }); |
| 727 | |
| 728 | test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () => |
| 729 | { |
| 730 | mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) => |
| 731 | { |
| 732 | res.type('text/vtt').send('WEBVTT\n'); |
| 733 | }; |
| 734 | |
| 735 | const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt'); |
| 736 | |
| 737 | expect(status).toBe(200); |
| 738 | expect(headers['content-type']).toMatch(/text\/vtt/); |
| 739 | expect(body.toString()).toBe('WEBVTT\n'); |
| 740 | }); |
| 741 | |
| 742 | test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () => |
| 743 | { |
| 744 | const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123'); |
| 745 | |
| 746 | expect(status).toBe(200); |
| 747 | expect(body).toEqual({ ok: true }); |
| 748 | expect(releasedVideoStreamSessionId).toBe('sess-123'); |
| 749 | }); |
| 750 | |
| 751 | test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () => |
| 752 | { |
| 753 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 754 | fs.writeFileSync(filePath, 'video'); |
| 755 | |
| 756 | let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 }); |
| 757 | expect(result.status).toBe(200); |
| 758 | expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' }); |
| 759 | |
| 760 | // A lower progress update should not downgrade the status. |
| 761 | result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 }); |
| 762 | expect(result.status).toBe(200); |
| 763 | expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' }); |
| 764 | |
| 765 | result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 766 | expect(result.status).toBe(200); |
| 767 | expect(result.body.watchedBy).toEqual({ admin: 'partway' }); |
| 768 | |
| 769 | result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 }); |
| 770 | expect(result.status).toBe(200); |
| 771 | expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' }); |
| 772 | |
| 773 | result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 774 | expect(result.status).toBe(200); |
| 775 | expect(result.body.watchedBy).toEqual({ admin: 'fully' }); |
| 776 | }); |
| 777 | }); |
| 778 | |
| 779 | describe('SHA-256 hashing and duplicate detection', () => |
| 780 | { |
| 781 | test('POST /api/files/upload stores sha256 hash for uploaded files', async () => |
| 782 | { |
| 783 | const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 784 | { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' }, |
| 785 | ]); |
| 786 | expect(status).toBe(200); |
| 787 | |
| 788 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 789 | .get([path.join(rootDir, 'hashme.txt')]); |
| 790 | expect(meta).toBeTruthy(); |
| 791 | // SHA-256 is a 64-char hex string. |
| 792 | expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 793 | }); |
| 794 | |
| 795 | test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () => |
| 796 | { |
| 797 | const filePath = path.join(rootDir, 'lazy.txt'); |
| 798 | fs.writeFileSync(filePath, 'lazy content'); |
| 799 | |
| 800 | // Insert a row without a hash to simulate a pre-existing file. |
| 801 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 802 | .run([filePath, 'admin', '[]']); |
| 803 | |
| 804 | const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 805 | expect(status).toBe(200); |
| 806 | expect(body.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 807 | |
| 808 | // Verify it was persisted. |
| 809 | const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]); |
| 810 | expect(row.sha256).toBe(body.sha256); |
| 811 | }); |
| 812 | |
| 813 | test('GET /api/files/duplicates returns other files with the same hash', async () => |
| 814 | { |
| 815 | const content = 'duplicate content'; |
| 816 | const fileA = path.join(rootDir, 'dup-a.txt'); |
| 817 | const fileB = path.join(rootDir, 'dup-b.txt'); |
| 818 | fs.writeFileSync(fileA, content); |
| 819 | fs.writeFileSync(fileB, content); |
| 820 | |
| 821 | // Compute the expected hash. |
| 822 | const crypto = require('crypto'); |
| 823 | const expectedHash = crypto.createHash('sha256').update(content).digest('hex'); |
| 824 | |
| 825 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 826 | .run([fileA, 'admin', '[]', expectedHash]); |
| 827 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 828 | .run([fileB, 'admin', '[]', expectedHash]); |
| 829 | |
| 830 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`); |
| 831 | expect(status).toBe(200); |
| 832 | expect(body.duplicates).toHaveLength(1); |
| 833 | expect(body.duplicates[0].path).toBe(fileB); |
| 834 | expect(body.duplicates[0].name).toBe('dup-b.txt'); |
| 835 | }); |
| 836 | |
| 837 | test('GET /api/files/duplicates returns empty list when no hash is stored', async () => |
| 838 | { |
| 839 | const filePath = path.join(rootDir, 'nohash.txt'); |
| 840 | fs.writeFileSync(filePath, 'no hash yet'); |
| 841 | |
| 842 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 843 | .run([filePath, 'admin', '[]']); |
| 844 | |
| 845 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`); |
| 846 | expect(status).toBe(200); |
| 847 | expect(body.duplicates).toEqual([]); |
| 848 | }); |
| 849 | |
| 850 | test('GET /api/files/duplicates excludes files outside accessible roots', async () => |
| 851 | { |
| 852 | const content = 'secret dupe'; |
| 853 | const accessible = path.join(rootDir, 'visible.txt'); |
| 854 | const outsideRoot = path.join(os.tmpdir(), 'outside.txt'); |
| 855 | fs.writeFileSync(accessible, content); |
| 856 | |
| 857 | const crypto = require('crypto'); |
| 858 | const hash = crypto.createHash('sha256').update(content).digest('hex'); |
| 859 | |
| 860 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 861 | .run([accessible, 'admin', '[]', hash]); |
| 862 | // Insert a row for a path that is NOT inside any configured root. |
| 863 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 864 | .run([outsideRoot, 'admin', '[]', hash]); |
| 865 | |
| 866 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`); |
| 867 | expect(status).toBe(200); |
| 868 | expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true); |
| 869 | }); |
| 870 | |
| 871 | test('POST /api/files/move preserves sha256 after rename', async () => |
| 872 | { |
| 873 | const from = path.join(rootDir, 'withHash.txt'); |
| 874 | const toDir = path.join(rootDir, 'subfolder'); |
| 875 | fs.writeFileSync(from, 'content'); |
| 876 | fs.mkdirSync(toDir); |
| 877 | |
| 878 | const hash = 'a'.repeat(64); |
| 879 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 880 | .run([from, 'admin', '[]', hash]); |
| 881 | |
| 882 | const { status } = await req('POST', '/api/files/move', { from, toDir }); |
| 883 | expect(status).toBe(200); |
| 884 | |
| 885 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 886 | .get([path.join(toDir, 'withHash.txt')]); |
| 887 | expect(meta.sha256).toBe(hash); |
| 888 | }); |
| 889 | }); |