| 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 mockUser = { username: 'testuser', isAdmin: true, permissions: {} }; |
| 12 | let mockVideoStreamSession = null; |
| 13 | let mockVideoStreamAsset = null; |
| 14 | |
| 15 | jest.mock('../server/db', () => |
| 16 | { |
| 17 | const { Database } = require('node-sqlite3-wasm'); |
| 18 | let db; |
| 19 | function getDb () |
| 20 | { |
| 21 | if (!db) |
| 22 | { |
| 23 | db = new Database(':memory:'); |
| 24 | db.exec(` |
| 25 | CREATE TABLE IF NOT EXISTS share_tokens ( |
| 26 | token TEXT PRIMARY KEY, |
| 27 | file_path TEXT NOT NULL, |
| 28 | is_dir INTEGER NOT NULL DEFAULT 0, |
| 29 | created_by TEXT NOT NULL, |
| 30 | created_at INTEGER NOT NULL, |
| 31 | expires_at INTEGER NOT NULL |
| 32 | ); |
| 33 | `); |
| 34 | } |
| 35 | return db; |
| 36 | } |
| 37 | return { getDb, initDb: getDb }; |
| 38 | }); |
| 39 | |
| 40 | jest.mock('../server/config', () => ({ |
| 41 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: {} }), |
| 42 | saveConfig: jest.fn(), |
| 43 | getEffectivePaths: (paths) => paths, |
| 44 | getAllowedRoot: (targetPath, roots) => |
| 45 | { |
| 46 | const pathMod = require('path'); |
| 47 | const absTarget = pathMod.resolve(String(targetPath || '')); |
| 48 | return roots.find((root) => |
| 49 | { |
| 50 | const absRoot = pathMod.resolve(root); |
| 51 | return absTarget === absRoot || absTarget.startsWith(absRoot + pathMod.sep); |
| 52 | }) || null; |
| 53 | }, |
| 54 | })); |
| 55 | |
| 56 | jest.mock('../server/auth', () => ({ |
| 57 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 58 | })); |
| 59 | |
| 60 | jest.mock('../server/video-stream', () => ({ |
| 61 | createVideoStreamSession: jest.fn(async () => |
| 62 | { |
| 63 | if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; |
| 64 | return mockVideoStreamSession || { sessionId: 'share-video-session', subtitleTracks: [] }; |
| 65 | }), |
| 66 | sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) => |
| 67 | { |
| 68 | if (typeof mockVideoStreamAsset === 'function') |
| 69 | { |
| 70 | await mockVideoStreamAsset(sessionId, assetPath, req, res); |
| 71 | return; |
| 72 | } |
| 73 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 74 | }), |
| 75 | })); |
| 76 | |
| 77 | const shareRoutes = require('../server/routes/share'); |
| 78 | const { getDb } = require('../server/db'); |
| 79 | |
| 80 | let server; |
| 81 | let baseUrl; |
| 82 | let rootDir; |
| 83 | |
| 84 | function get (p) { return fetch(baseUrl + p); } |
| 85 | function post (p, body) { |
| 86 | return fetch(baseUrl + p, { |
| 87 | method: 'POST', |
| 88 | headers: { 'Content-Type': 'application/json' }, |
| 89 | body: JSON.stringify(body), |
| 90 | }); |
| 91 | } |
| 92 | |
| 93 | beforeAll(async () => |
| 94 | { |
| 95 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-test-')); |
| 96 | mockPaths = [rootDir]; |
| 97 | |
| 98 | const app = express(); |
| 99 | app.use(express.json()); |
| 100 | app.use('/api/share', shareRoutes); |
| 101 | app.use((err, req, res, _next) => |
| 102 | { |
| 103 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 104 | }); |
| 105 | |
| 106 | server = http.createServer(app); |
| 107 | server.listen(0); |
| 108 | await once(server, 'listening'); |
| 109 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 110 | }); |
| 111 | |
| 112 | afterAll(() => |
| 113 | { |
| 114 | server.close(); |
| 115 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 116 | }); |
| 117 | |
| 118 | beforeEach(() => |
| 119 | { |
| 120 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 121 | fs.mkdirSync(rootDir, { recursive: true }); |
| 122 | mockVideoStreamSession = null; |
| 123 | mockVideoStreamAsset = null; |
| 124 | // Reset DB between tests |
| 125 | const db = getDb(); |
| 126 | db.exec('DELETE FROM share_tokens'); |
| 127 | }); |
| 128 | |
| 129 | // --------------------------------------------------------------------------- |
| 130 | // POST /api/share/create |
| 131 | // --------------------------------------------------------------------------- |
| 132 | describe('POST /api/share/create', () => |
| 133 | { |
| 134 | test('creates a token for a file', async () => |
| 135 | { |
| 136 | const filePath = path.join(rootDir, 'hello.txt'); |
| 137 | fs.writeFileSync(filePath, 'hello'); |
| 138 | |
| 139 | const res = await post('/api/share/create', { filePath }); |
| 140 | expect(res.status).toBe(200); |
| 141 | const body = await res.json(); |
| 142 | expect(typeof body.token).toBe('string'); |
| 143 | expect(body.token).toHaveLength(64); // 32 bytes hex |
| 144 | expect(typeof body.expiresAt).toBe('number'); |
| 145 | expect(body.expiresAt).toBeGreaterThan(Date.now()); |
| 146 | }); |
| 147 | |
| 148 | test('creates a token for a directory', async () => |
| 149 | { |
| 150 | const dirPath = path.join(rootDir, 'subdir'); |
| 151 | fs.mkdirSync(dirPath); |
| 152 | |
| 153 | const res = await post('/api/share/create', { filePath: dirPath }); |
| 154 | expect(res.status).toBe(200); |
| 155 | const body = await res.json(); |
| 156 | expect(typeof body.token).toBe('string'); |
| 157 | }); |
| 158 | |
| 159 | test('returns 400 when filePath is missing', async () => |
| 160 | { |
| 161 | const res = await post('/api/share/create', {}); |
| 162 | expect(res.status).toBe(400); |
| 163 | }); |
| 164 | |
| 165 | test('returns 403 when path is outside configured roots', async () => |
| 166 | { |
| 167 | const res = await post('/api/share/create', { filePath: os.tmpdir() }); |
| 168 | expect(res.status).toBe(403); |
| 169 | }); |
| 170 | |
| 171 | test('returns 404 when file does not exist', async () => |
| 172 | { |
| 173 | const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') }); |
| 174 | expect(res.status).toBe(404); |
| 175 | }); |
| 176 | }); |
| 177 | |
| 178 | // --------------------------------------------------------------------------- |
| 179 | // GET /api/share/info/:token |
| 180 | // --------------------------------------------------------------------------- |
| 181 | describe('GET /api/share/info/:token', () => |
| 182 | { |
| 183 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 184 | { |
| 185 | getDb().prepare( |
| 186 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 187 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 188 | } |
| 189 | |
| 190 | test('returns file info for a valid token', async () => |
| 191 | { |
| 192 | const filePath = path.join(rootDir, 'info.txt'); |
| 193 | fs.writeFileSync(filePath, 'data'); |
| 194 | insertToken({ token: 'aaaa', filePath }); |
| 195 | |
| 196 | const res = await get('/api/share/info/aaaa'); |
| 197 | expect(res.status).toBe(200); |
| 198 | const body = await res.json(); |
| 199 | expect(body.name).toBe('info.txt'); |
| 200 | expect(body.isDir).toBe(false); |
| 201 | expect(typeof body.expiresAt).toBe('number'); |
| 202 | }); |
| 203 | |
| 204 | test('returns isDir=true for directory tokens', async () => |
| 205 | { |
| 206 | const dirPath = path.join(rootDir, 'mydir'); |
| 207 | fs.mkdirSync(dirPath); |
| 208 | insertToken({ token: 'bbbb', filePath: dirPath, isDir: 1 }); |
| 209 | |
| 210 | const res = await get('/api/share/info/bbbb'); |
| 211 | expect(res.status).toBe(200); |
| 212 | const body = await res.json(); |
| 213 | expect(body.isDir).toBe(true); |
| 214 | }); |
| 215 | |
| 216 | test('returns 404 for unknown token', async () => |
| 217 | { |
| 218 | const res = await get('/api/share/info/unknowntoken'); |
| 219 | expect(res.status).toBe(404); |
| 220 | }); |
| 221 | |
| 222 | test('returns 410 for expired token', async () => |
| 223 | { |
| 224 | const filePath = path.join(rootDir, 'exp.txt'); |
| 225 | fs.writeFileSync(filePath, 'x'); |
| 226 | insertToken({ token: 'cccc', filePath, expiresAt: Date.now() - 1000 }); |
| 227 | |
| 228 | const res = await get('/api/share/info/cccc'); |
| 229 | expect(res.status).toBe(410); |
| 230 | }); |
| 231 | }); |
| 232 | |
| 233 | // --------------------------------------------------------------------------- |
| 234 | // GET /api/share/preview/:token |
| 235 | // --------------------------------------------------------------------------- |
| 236 | describe('GET /api/share/preview/:token', () => |
| 237 | { |
| 238 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 239 | { |
| 240 | getDb().prepare( |
| 241 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 242 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 243 | } |
| 244 | |
| 245 | test('streams file content for a valid file token', async () => |
| 246 | { |
| 247 | const filePath = path.join(rootDir, 'preview.txt'); |
| 248 | fs.writeFileSync(filePath, 'preview content'); |
| 249 | insertToken({ token: 'prev1', filePath }); |
| 250 | |
| 251 | const res = await get('/api/share/preview/prev1'); |
| 252 | expect(res.status).toBe(200); |
| 253 | const text = await res.text(); |
| 254 | expect(text).toBe('preview content'); |
| 255 | }); |
| 256 | |
| 257 | test('returns 400 when token points to a directory', async () => |
| 258 | { |
| 259 | const dirPath = path.join(rootDir, 'previewdir'); |
| 260 | fs.mkdirSync(dirPath); |
| 261 | insertToken({ token: 'prev2', filePath: dirPath, isDir: 1 }); |
| 262 | |
| 263 | const res = await get('/api/share/preview/prev2'); |
| 264 | expect(res.status).toBe(400); |
| 265 | }); |
| 266 | |
| 267 | test('returns 410 for expired token', async () => |
| 268 | { |
| 269 | const filePath = path.join(rootDir, 'ep.txt'); |
| 270 | fs.writeFileSync(filePath, 'x'); |
| 271 | insertToken({ token: 'prev3', filePath, expiresAt: Date.now() - 1 }); |
| 272 | |
| 273 | const res = await get('/api/share/preview/prev3'); |
| 274 | expect(res.status).toBe(410); |
| 275 | }); |
| 276 | }); |
| 277 | |
| 278 | describe('GET /api/share/video-stream/:token', () => |
| 279 | { |
| 280 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 281 | { |
| 282 | getDb().prepare( |
| 283 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 284 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 285 | } |
| 286 | |
| 287 | test('creates a stream session for a shared video', async () => |
| 288 | { |
| 289 | const filePath = path.join(rootDir, 'movie.mkv'); |
| 290 | fs.writeFileSync(filePath, 'video'); |
| 291 | insertToken({ token: 'stream1', filePath }); |
| 292 | mockVideoStreamSession = { |
| 293 | sessionId: 'share-sess-1', |
| 294 | durationSeconds: 42.25, |
| 295 | subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], |
| 296 | }; |
| 297 | |
| 298 | const res = await get('/api/share/video-stream/stream1'); |
| 299 | expect(res.status).toBe(200); |
| 300 | const body = await res.json(); |
| 301 | expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8'); |
| 302 | expect(body.durationSeconds).toBe(42.25); |
| 303 | expect(body.subtitleTracks).toEqual([ |
| 304 | { |
| 305 | label: 'English', |
| 306 | language: 'eng', |
| 307 | default: true, |
| 308 | src: '/api/share/video-stream/session/share-sess-1/subtitle-0.vtt', |
| 309 | }, |
| 310 | ]); |
| 311 | }); |
| 312 | |
| 313 | test('serves stream assets from an existing share session', async () => |
| 314 | { |
| 315 | mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) => |
| 316 | { |
| 317 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 318 | }; |
| 319 | |
| 320 | const res = await get('/api/share/video-stream/session/share-sess-1/master.m3u8'); |
| 321 | expect(res.status).toBe(200); |
| 322 | expect(await res.text()).toBe('#EXTM3U\n'); |
| 323 | }); |
| 324 | }); |
| 325 | |
| 326 | // --------------------------------------------------------------------------- |
| 327 | // GET /api/share/download/:token |
| 328 | // --------------------------------------------------------------------------- |
| 329 | describe('GET /api/share/download/:token', () => |
| 330 | { |
| 331 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 332 | { |
| 333 | getDb().prepare( |
| 334 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 335 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 336 | } |
| 337 | |
| 338 | test('downloads a file', async () => |
| 339 | { |
| 340 | const filePath = path.join(rootDir, 'dl.txt'); |
| 341 | fs.writeFileSync(filePath, 'download me'); |
| 342 | insertToken({ token: 'dl01', filePath }); |
| 343 | |
| 344 | const res = await get('/api/share/download/dl01'); |
| 345 | expect(res.status).toBe(200); |
| 346 | const text = await res.text(); |
| 347 | expect(text).toBe('download me'); |
| 348 | }); |
| 349 | |
| 350 | test('downloads a directory as zip', async () => |
| 351 | { |
| 352 | const dirPath = path.join(rootDir, 'zipit'); |
| 353 | fs.mkdirSync(dirPath); |
| 354 | fs.writeFileSync(path.join(dirPath, 'a.txt'), 'aaa'); |
| 355 | insertToken({ token: 'dl02', filePath: dirPath, isDir: 1 }); |
| 356 | |
| 357 | const res = await get('/api/share/download/dl02'); |
| 358 | expect(res.status).toBe(200); |
| 359 | const ct = res.headers.get('content-type') || ''; |
| 360 | // Express sends application/zip or application/octet-stream for .zip downloads |
| 361 | expect(ct.includes('zip') || ct.includes('octet')).toBe(true); |
| 362 | const buf = await res.arrayBuffer(); |
| 363 | // ZIP magic bytes: PK\x03\x04 |
| 364 | expect(new Uint8Array(buf.slice(0, 4))).toEqual(new Uint8Array([0x50, 0x4b, 0x03, 0x04])); |
| 365 | }); |
| 366 | |
| 367 | test('returns 410 for expired token', async () => |
| 368 | { |
| 369 | const filePath = path.join(rootDir, 'edl.txt'); |
| 370 | fs.writeFileSync(filePath, 'x'); |
| 371 | insertToken({ token: 'dl03', filePath, expiresAt: Date.now() - 1 }); |
| 372 | |
| 373 | const res = await get('/api/share/download/dl03'); |
| 374 | expect(res.status).toBe(410); |
| 375 | }); |
| 376 | |
| 377 | test('returns 404 for unknown token', async () => |
| 378 | { |
| 379 | const res = await get('/api/share/download/nosuchtoken'); |
| 380 | expect(res.status).toBe(404); |
| 381 | }); |
| 382 | }); |
| 383 | |
| 384 | // --------------------------------------------------------------------------- |
| 385 | // pruneZipCache |
| 386 | // --------------------------------------------------------------------------- |
| 387 | describe('pruneZipCache', () => |
| 388 | { |
| 389 | test('deletes zip files older than 1 day', () => |
| 390 | { |
| 391 | const { pruneZipCache, ZIP_CACHE_DIR } = require('../server/routes/share'); |
| 392 | fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true }); |
| 393 | |
| 394 | const oldZip = path.join(ZIP_CACHE_DIR, 'old.zip'); |
| 395 | fs.writeFileSync(oldZip, 'fake zip'); |
| 396 | // Back-date the mtime by 25 hours |
| 397 | const pastTime = new Date(Date.now() - 25 * 60 * 60 * 1000); |
| 398 | fs.utimesSync(oldZip, pastTime, pastTime); |
| 399 | |
| 400 | const freshZip = path.join(ZIP_CACHE_DIR, 'fresh.zip'); |
| 401 | fs.writeFileSync(freshZip, 'fake fresh zip'); |
| 402 | |
| 403 | pruneZipCache(); |
| 404 | |
| 405 | expect(fs.existsSync(oldZip)).toBe(false); |
| 406 | expect(fs.existsSync(freshZip)).toBe(true); |
| 407 | |
| 408 | // Cleanup |
| 409 | try { fs.unlinkSync(freshZip); } catch { /* ignore */ } |
| 410 | }); |
| 411 | }); |