| 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 mockUserPath = null; |
| 12 | let mockUser = { username: 'testuser', isAdmin: true, permissions: {} }; |
| 13 | let mockVideoStreamSession = null; |
| 14 | let mockVideoStreamAsset = null; |
| 15 | let releasedVideoStreamSessionId = null; |
| 16 | let mockSubtitleFrameResult = null; |
| 17 | let mockSubtitleFrameError = null; |
| 18 | let mockSubtitleRangeResult = null; |
| 19 | let mockSubtitleRangeError = 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 share_tokens ( |
| 32 | token TEXT PRIMARY KEY, |
| 33 | file_path TEXT NOT NULL, |
| 34 | is_dir INTEGER NOT NULL DEFAULT 0, |
| 35 | created_by TEXT NOT NULL, |
| 36 | created_at INTEGER NOT NULL, |
| 37 | expires_at INTEGER NOT NULL |
| 38 | ); |
| 39 | `); |
| 40 | } |
| 41 | return db; |
| 42 | } |
| 43 | return { getDb, initDb: getDb }; |
| 44 | }); |
| 45 | |
| 46 | jest.mock('../server/config', () => ({ |
| 47 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: {} }), |
| 48 | saveConfig: jest.fn(), |
| 49 | getEffectivePaths: (paths) => paths, |
| 50 | getAllowedRoot: (targetPath, roots) => |
| 51 | { |
| 52 | const pathMod = require('path'); |
| 53 | const absTarget = pathMod.resolve(String(targetPath || '')); |
| 54 | return roots.find((root) => |
| 55 | { |
| 56 | const absRoot = pathMod.resolve(root); |
| 57 | return absTarget === absRoot || absTarget.startsWith(absRoot + pathMod.sep); |
| 58 | }) || null; |
| 59 | }, |
| 60 | })); |
| 61 | |
| 62 | jest.mock('../server/auth', () => ({ |
| 63 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 64 | })); |
| 65 | |
| 66 | jest.mock('../server/video-stream', () => ({ |
| 67 | createVideoStreamSession: jest.fn(async () => |
| 68 | { |
| 69 | if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; |
| 70 | return mockVideoStreamSession || { sessionId: 'share-video-session', subtitleTracks: [] }; |
| 71 | }), |
| 72 | sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) => |
| 73 | { |
| 74 | if (typeof mockVideoStreamAsset === 'function') |
| 75 | { |
| 76 | await mockVideoStreamAsset(sessionId, assetPath, req, res); |
| 77 | return; |
| 78 | } |
| 79 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 80 | }), |
| 81 | releaseVideoStreamSession: jest.fn((sessionId) => |
| 82 | { |
| 83 | releasedVideoStreamSessionId = sessionId; |
| 84 | }), |
| 85 | })); |
| 86 | |
| 87 | jest.mock('../server/image-subtitles', () => ({ |
| 88 | renderImageSubtitleFrame: jest.fn(async () => |
| 89 | { |
| 90 | if (mockSubtitleFrameError) throw mockSubtitleFrameError; |
| 91 | return mockSubtitleFrameResult; |
| 92 | }), |
| 93 | renderImageSubtitleFramesInRange: jest.fn(async () => |
| 94 | { |
| 95 | if (mockSubtitleRangeError) throw mockSubtitleRangeError; |
| 96 | return mockSubtitleRangeResult; |
| 97 | }), |
| 98 | })); |
| 99 | |
| 100 | jest.mock('../server/logger', () => ({ |
| 101 | logError: jest.fn(), |
| 102 | })); |
| 103 | |
| 104 | jest.mock('../server/subtitle-debug-log', () => ({ |
| 105 | appendSubtitleDebugEntries: jest.fn(), |
| 106 | })); |
| 107 | |
| 108 | const shareRoutes = require('../server/routes/share'); |
| 109 | const { getDb } = require('../server/db'); |
| 110 | |
| 111 | let server; |
| 112 | let baseUrl; |
| 113 | let rootDir; |
| 114 | |
| 115 | function get (p) { return fetch(baseUrl + p); } |
| 116 | function post (p, body) |
| 117 | { |
| 118 | return fetch(baseUrl + p, { |
| 119 | method: 'POST', |
| 120 | headers: { 'Content-Type': 'application/json' }, |
| 121 | body: JSON.stringify(body), |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | beforeAll(async () => |
| 126 | { |
| 127 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-test-')); |
| 128 | mockPaths = [rootDir]; |
| 129 | |
| 130 | const app = express(); |
| 131 | app.use(express.json()); |
| 132 | app.use('/api/share', shareRoutes); |
| 133 | app.use((err, req, res, _next) => |
| 134 | { |
| 135 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 136 | }); |
| 137 | |
| 138 | server = http.createServer(app); |
| 139 | server.listen(0); |
| 140 | await once(server, 'listening'); |
| 141 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 142 | }); |
| 143 | |
| 144 | afterAll(() => |
| 145 | { |
| 146 | server.close(); |
| 147 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 148 | }); |
| 149 | |
| 150 | beforeEach(() => |
| 151 | { |
| 152 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 153 | fs.mkdirSync(rootDir, { recursive: true }); |
| 154 | if (mockUserPath) |
| 155 | { |
| 156 | fs.rmSync(mockUserPath, { recursive: true, force: true }); |
| 157 | fs.mkdirSync(mockUserPath, { recursive: true }); |
| 158 | } |
| 159 | mockUserPath = null; |
| 160 | mockVideoStreamSession = null; |
| 161 | mockVideoStreamAsset = null; |
| 162 | releasedVideoStreamSessionId = null; |
| 163 | mockSubtitleFrameResult = null; |
| 164 | mockSubtitleFrameError = null; |
| 165 | mockSubtitleRangeResult = null; |
| 166 | mockSubtitleRangeError = null; |
| 167 | // Reset DB between tests |
| 168 | const db = getDb(); |
| 169 | db.exec('DELETE FROM share_tokens'); |
| 170 | }); |
| 171 | |
| 172 | // --------------------------------------------------------------------------- |
| 173 | // POST /api/share/create |
| 174 | // --------------------------------------------------------------------------- |
| 175 | describe('POST /api/share/create', () => |
| 176 | { |
| 177 | test('creates a token for a file', async () => |
| 178 | { |
| 179 | const filePath = path.join(rootDir, 'hello.txt'); |
| 180 | fs.writeFileSync(filePath, 'hello'); |
| 181 | |
| 182 | const res = await post('/api/share/create', { filePath }); |
| 183 | expect(res.status).toBe(200); |
| 184 | const body = await res.json(); |
| 185 | expect(typeof body.token).toBe('string'); |
| 186 | expect(body.token).toHaveLength(64); // 32 bytes hex |
| 187 | expect(typeof body.expiresAt).toBe('number'); |
| 188 | expect(body.expiresAt).toBeGreaterThan(Date.now()); |
| 189 | }); |
| 190 | |
| 191 | test('creates a token for a directory', async () => |
| 192 | { |
| 193 | const dirPath = path.join(rootDir, 'subdir'); |
| 194 | fs.mkdirSync(dirPath); |
| 195 | |
| 196 | const res = await post('/api/share/create', { filePath: dirPath }); |
| 197 | expect(res.status).toBe(200); |
| 198 | const body = await res.json(); |
| 199 | expect(typeof body.token).toBe('string'); |
| 200 | }); |
| 201 | |
| 202 | test('returns 400 when filePath is missing', async () => |
| 203 | { |
| 204 | const res = await post('/api/share/create', {}); |
| 205 | expect(res.status).toBe(400); |
| 206 | }); |
| 207 | |
| 208 | test('returns 403 when path is outside configured roots', async () => |
| 209 | { |
| 210 | const res = await post('/api/share/create', { filePath: os.tmpdir() }); |
| 211 | expect(res.status).toBe(403); |
| 212 | }); |
| 213 | |
| 214 | test('returns 404 when file does not exist', async () => |
| 215 | { |
| 216 | const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') }); |
| 217 | expect(res.status).toBe(404); |
| 218 | }); |
| 219 | |
| 220 | test('creates a token for a file inside My Folder', async () => |
| 221 | { |
| 222 | const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-userfolders-')); |
| 223 | const userFolder = path.join(userFolderBase, 'testuser'); |
| 224 | const filePath = path.join(userFolder, 'private.txt'); |
| 225 | |
| 226 | mockUserPath = userFolderBase; |
| 227 | mockUser = { username: 'testuser', isAdmin: false, permissions: {} }; |
| 228 | fs.mkdirSync(userFolder, { recursive: true }); |
| 229 | fs.writeFileSync(filePath, 'private'); |
| 230 | |
| 231 | try |
| 232 | { |
| 233 | const res = await post('/api/share/create', { filePath }); |
| 234 | expect(res.status).toBe(200); |
| 235 | const body = await res.json(); |
| 236 | expect(typeof body.token).toBe('string'); |
| 237 | } finally |
| 238 | { |
| 239 | fs.rmSync(userFolderBase, { recursive: true, force: true }); |
| 240 | } |
| 241 | }); |
| 242 | }); |
| 243 | |
| 244 | // --------------------------------------------------------------------------- |
| 245 | // GET /api/share/info/:token |
| 246 | // --------------------------------------------------------------------------- |
| 247 | describe('GET /api/share/info/:token', () => |
| 248 | { |
| 249 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 250 | { |
| 251 | getDb().prepare( |
| 252 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 253 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 254 | } |
| 255 | |
| 256 | test('returns file info for a valid token', async () => |
| 257 | { |
| 258 | const filePath = path.join(rootDir, 'info.txt'); |
| 259 | fs.writeFileSync(filePath, 'data'); |
| 260 | insertToken({ token: 'aaaa', filePath }); |
| 261 | |
| 262 | const res = await get('/api/share/info/aaaa'); |
| 263 | expect(res.status).toBe(200); |
| 264 | const body = await res.json(); |
| 265 | expect(body.name).toBe('info.txt'); |
| 266 | expect(body.isDir).toBe(false); |
| 267 | expect(typeof body.expiresAt).toBe('number'); |
| 268 | }); |
| 269 | |
| 270 | test('returns isDir=true for directory tokens', async () => |
| 271 | { |
| 272 | const dirPath = path.join(rootDir, 'mydir'); |
| 273 | fs.mkdirSync(dirPath); |
| 274 | insertToken({ token: 'bbbb', filePath: dirPath, isDir: 1 }); |
| 275 | |
| 276 | const res = await get('/api/share/info/bbbb'); |
| 277 | expect(res.status).toBe(200); |
| 278 | const body = await res.json(); |
| 279 | expect(body.isDir).toBe(true); |
| 280 | }); |
| 281 | |
| 282 | test('returns 404 for unknown token', async () => |
| 283 | { |
| 284 | const res = await get('/api/share/info/unknowntoken'); |
| 285 | expect(res.status).toBe(404); |
| 286 | }); |
| 287 | |
| 288 | test('returns 410 for expired token', async () => |
| 289 | { |
| 290 | const filePath = path.join(rootDir, 'exp.txt'); |
| 291 | fs.writeFileSync(filePath, 'x'); |
| 292 | insertToken({ token: 'cccc', filePath, expiresAt: Date.now() - 1000 }); |
| 293 | |
| 294 | const res = await get('/api/share/info/cccc'); |
| 295 | expect(res.status).toBe(410); |
| 296 | }); |
| 297 | }); |
| 298 | |
| 299 | // --------------------------------------------------------------------------- |
| 300 | // GET /api/share/preview/:token |
| 301 | // --------------------------------------------------------------------------- |
| 302 | describe('GET /api/share/preview/:token', () => |
| 303 | { |
| 304 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 305 | { |
| 306 | getDb().prepare( |
| 307 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 308 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 309 | } |
| 310 | |
| 311 | test('streams file content for a valid file token', async () => |
| 312 | { |
| 313 | const filePath = path.join(rootDir, 'preview.txt'); |
| 314 | fs.writeFileSync(filePath, 'preview content'); |
| 315 | insertToken({ token: 'prev1', filePath }); |
| 316 | |
| 317 | const res = await get('/api/share/preview/prev1'); |
| 318 | expect(res.status).toBe(200); |
| 319 | const text = await res.text(); |
| 320 | expect(text).toBe('preview content'); |
| 321 | }); |
| 322 | |
| 323 | test('returns 400 when token points to a directory', async () => |
| 324 | { |
| 325 | const dirPath = path.join(rootDir, 'previewdir'); |
| 326 | fs.mkdirSync(dirPath); |
| 327 | insertToken({ token: 'prev2', filePath: dirPath, isDir: 1 }); |
| 328 | |
| 329 | const res = await get('/api/share/preview/prev2'); |
| 330 | expect(res.status).toBe(400); |
| 331 | }); |
| 332 | |
| 333 | test('returns 410 for expired token', async () => |
| 334 | { |
| 335 | const filePath = path.join(rootDir, 'ep.txt'); |
| 336 | fs.writeFileSync(filePath, 'x'); |
| 337 | insertToken({ token: 'prev3', filePath, expiresAt: Date.now() - 1 }); |
| 338 | |
| 339 | const res = await get('/api/share/preview/prev3'); |
| 340 | expect(res.status).toBe(410); |
| 341 | }); |
| 342 | }); |
| 343 | |
| 344 | describe('GET /api/share/video-stream/:token', () => |
| 345 | { |
| 346 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 347 | { |
| 348 | getDb().prepare( |
| 349 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 350 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 351 | } |
| 352 | |
| 353 | test('creates a stream session for a shared video', async () => |
| 354 | { |
| 355 | const filePath = path.join(rootDir, 'movie.mkv'); |
| 356 | fs.writeFileSync(filePath, 'video'); |
| 357 | insertToken({ token: 'stream1', filePath }); |
| 358 | mockVideoStreamSession = { |
| 359 | sessionId: 'share-sess-1', |
| 360 | durationSeconds: 42.25, |
| 361 | subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], |
| 362 | }; |
| 363 | |
| 364 | const res = await get('/api/share/video-stream/stream1'); |
| 365 | expect(res.status).toBe(200); |
| 366 | const body = await res.json(); |
| 367 | expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8'); |
| 368 | expect(body.durationSeconds).toBe(42.25); |
| 369 | expect(body.subtitleTracks).toEqual([ |
| 370 | { |
| 371 | label: 'English', |
| 372 | language: 'eng', |
| 373 | default: true, |
| 374 | src: '/api/share/video-stream/session/share-sess-1/subtitle-0.vtt', |
| 375 | }, |
| 376 | ]); |
| 377 | }); |
| 378 | |
| 379 | test('serves stream assets from an existing share session', async () => |
| 380 | { |
| 381 | mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) => |
| 382 | { |
| 383 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 384 | }; |
| 385 | |
| 386 | const res = await get('/api/share/video-stream/session/share-sess-1/master.m3u8'); |
| 387 | expect(res.status).toBe(200); |
| 388 | expect(await res.text()).toBe('#EXTM3U\n'); |
| 389 | }); |
| 390 | |
| 391 | test('releases an existing share stream session', async () => |
| 392 | { |
| 393 | const res = await fetch(baseUrl + '/api/share/video-stream/session/share-sess-1', { |
| 394 | method: 'DELETE', |
| 395 | }); |
| 396 | |
| 397 | expect(res.status).toBe(200); |
| 398 | expect(await res.json()).toEqual({ ok: true }); |
| 399 | expect(releasedVideoStreamSessionId).toBe('share-sess-1'); |
| 400 | }); |
| 401 | |
| 402 | test('renders image subtitle frames for a shared video', async () => |
| 403 | { |
| 404 | const filePath = path.join(rootDir, 'movie-subs.mkv'); |
| 405 | fs.writeFileSync(filePath, 'video'); |
| 406 | insertToken({ token: 'stream-subs', filePath }); |
| 407 | mockSubtitleFrameResult = { |
| 408 | frame: Buffer.from('png-data'), |
| 409 | left: 100, |
| 410 | top: 50, |
| 411 | width: 320, |
| 412 | height: 180, |
| 413 | canvasWidth: 640, |
| 414 | canvasHeight: 360, |
| 415 | startTimeSeconds: 1.5, |
| 416 | endTimeSeconds: 3.2, |
| 417 | }; |
| 418 | |
| 419 | const res = await get('/api/share/video-stream-subtitle-frame/stream-subs?streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080'); |
| 420 | |
| 421 | expect(res.status).toBe(200); |
| 422 | expect(res.headers.get('content-type')).toMatch(/image\/png/); |
| 423 | expect(res.headers.get('x-subtitle-frame-status')).toBe('ok'); |
| 424 | expect(res.headers.get('x-subtitle-frame-left')).toBe('100'); |
| 425 | expect(res.headers.get('x-subtitle-frame-top')).toBe('50'); |
| 426 | expect(res.headers.get('x-subtitle-frame-width')).toBe('320'); |
| 427 | expect(res.headers.get('x-subtitle-frame-height')).toBe('180'); |
| 428 | expect(res.headers.get('x-subtitle-frame-canvas-width')).toBe('640'); |
| 429 | expect(res.headers.get('x-subtitle-frame-canvas-height')).toBe('360'); |
| 430 | expect(res.headers.get('x-subtitle-frame-start-time')).toBe('1.5'); |
| 431 | expect(res.headers.get('x-subtitle-frame-end-time')).toBe('3.2'); |
| 432 | expect(Number(res.headers.get('x-subtitle-request-received-at-ms'))).toBeGreaterThan(0); |
| 433 | expect(Number(res.headers.get('x-subtitle-response-sent-at-ms'))).toBeGreaterThan(0); |
| 434 | expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from('png-data'))).toBe(true); |
| 435 | }); |
| 436 | |
| 437 | test('renders image subtitle frames for a shared video range request', async () => |
| 438 | { |
| 439 | const filePath = path.join(rootDir, 'movie-subs.mkv'); |
| 440 | fs.writeFileSync(filePath, 'video'); |
| 441 | insertToken({ token: 'stream-subs-range', filePath }); |
| 442 | mockSubtitleRangeResult = { |
| 443 | frames: [ |
| 444 | { |
| 445 | frame: Buffer.from('png-a'), |
| 446 | left: 10, |
| 447 | top: 20, |
| 448 | width: 300, |
| 449 | height: 90, |
| 450 | canvasWidth: 640, |
| 451 | canvasHeight: 360, |
| 452 | startTimeSeconds: 2, |
| 453 | endTimeSeconds: 4, |
| 454 | }, |
| 455 | ], |
| 456 | }; |
| 457 | |
| 458 | const res = await get('/api/share/video-stream-subtitle-range/stream-subs-range?streamIndex=0&startTimeSeconds=2&endTimeSeconds=8&videoWidth=1920&videoHeight=1080'); |
| 459 | |
| 460 | expect(res.status).toBe(200); |
| 461 | expect(await res.json()).toEqual(expect.objectContaining({ |
| 462 | status: 'ok', |
| 463 | startTimeSeconds: 2, |
| 464 | endTimeSeconds: 8, |
| 465 | frames: [expect.objectContaining({ |
| 466 | left: 10, |
| 467 | top: 20, |
| 468 | width: 300, |
| 469 | height: 90, |
| 470 | canvasWidth: 640, |
| 471 | canvasHeight: 360, |
| 472 | startTimeSeconds: 2, |
| 473 | endTimeSeconds: 4, |
| 474 | contentType: 'image/png', |
| 475 | frameBase64: Buffer.from('png-a').toString('base64'), |
| 476 | })], |
| 477 | })); |
| 478 | }); |
| 479 | |
| 480 | test('persists subtitle debug batches for shared video playback', async () => |
| 481 | { |
| 482 | const filePath = path.join(rootDir, 'movie-subs.mkv'); |
| 483 | fs.writeFileSync(filePath, 'video'); |
| 484 | insertToken({ token: 'stream-subs-log', filePath }); |
| 485 | const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log'); |
| 486 | |
| 487 | const res = await post('/api/share/video-stream-subtitle-log/stream-subs-log', { |
| 488 | sessionId: 'share-sess-1', |
| 489 | entries: [ |
| 490 | { loggedAtMs: 1000, eventType: 'subtitle_png_requested' }, |
| 491 | ], |
| 492 | }); |
| 493 | |
| 494 | expect(res.status).toBe(200); |
| 495 | expect(await res.json()).toEqual({ ok: true }); |
| 496 | expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({ |
| 497 | videoName: 'movie-subs.mkv', |
| 498 | context: expect.objectContaining({ |
| 499 | filePath, |
| 500 | sessionId: 'share-sess-1', |
| 501 | source: 'share', |
| 502 | shareToken: 'stream-subs-log', |
| 503 | }), |
| 504 | })); |
| 505 | }); |
| 506 | }); |
| 507 | |
| 508 | // --------------------------------------------------------------------------- |
| 509 | // GET /api/share/download/:token |
| 510 | // --------------------------------------------------------------------------- |
| 511 | describe('GET /api/share/download/:token', () => |
| 512 | { |
| 513 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 514 | { |
| 515 | getDb().prepare( |
| 516 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 517 | ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 518 | } |
| 519 | |
| 520 | test('downloads a file', async () => |
| 521 | { |
| 522 | const filePath = path.join(rootDir, 'dl.txt'); |
| 523 | fs.writeFileSync(filePath, 'download me'); |
| 524 | insertToken({ token: 'dl01', filePath }); |
| 525 | |
| 526 | const res = await get('/api/share/download/dl01'); |
| 527 | expect(res.status).toBe(200); |
| 528 | const text = await res.text(); |
| 529 | expect(text).toBe('download me'); |
| 530 | }); |
| 531 | |
| 532 | test('downloads a directory as zip', async () => |
| 533 | { |
| 534 | const dirPath = path.join(rootDir, 'zipit'); |
| 535 | fs.mkdirSync(dirPath); |
| 536 | fs.writeFileSync(path.join(dirPath, 'a.txt'), 'aaa'); |
| 537 | insertToken({ token: 'dl02', filePath: dirPath, isDir: 1 }); |
| 538 | |
| 539 | const res = await get('/api/share/download/dl02'); |
| 540 | expect(res.status).toBe(200); |
| 541 | const ct = res.headers.get('content-type') || ''; |
| 542 | // Express sends application/zip or application/octet-stream for .zip downloads |
| 543 | expect(ct.includes('zip') || ct.includes('octet')).toBe(true); |
| 544 | const buf = await res.arrayBuffer(); |
| 545 | // ZIP magic bytes: PK\x03\x04 |
| 546 | expect(new Uint8Array(buf.slice(0, 4))).toEqual(new Uint8Array([0x50, 0x4b, 0x03, 0x04])); |
| 547 | }); |
| 548 | |
| 549 | test('returns 410 for expired token', async () => |
| 550 | { |
| 551 | const filePath = path.join(rootDir, 'edl.txt'); |
| 552 | fs.writeFileSync(filePath, 'x'); |
| 553 | insertToken({ token: 'dl03', filePath, expiresAt: Date.now() - 1 }); |
| 554 | |
| 555 | const res = await get('/api/share/download/dl03'); |
| 556 | expect(res.status).toBe(410); |
| 557 | }); |
| 558 | |
| 559 | test('returns 404 for unknown token', async () => |
| 560 | { |
| 561 | const res = await get('/api/share/download/nosuchtoken'); |
| 562 | expect(res.status).toBe(404); |
| 563 | }); |
| 564 | }); |
| 565 | |
| 566 | // --------------------------------------------------------------------------- |
| 567 | // pruneZipCache |
| 568 | // --------------------------------------------------------------------------- |
| 569 | describe('pruneZipCache', () => |
| 570 | { |
| 571 | test('deletes zip files older than 1 day', () => |
| 572 | { |
| 573 | const { pruneZipCache, ZIP_CACHE_DIR } = require('../server/routes/share'); |
| 574 | fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true }); |
| 575 | |
| 576 | const oldZip = path.join(ZIP_CACHE_DIR, 'old.zip'); |
| 577 | fs.writeFileSync(oldZip, 'fake zip'); |
| 578 | // Back-date the mtime by 25 hours |
| 579 | const pastTime = new Date(Date.now() - 25 * 60 * 60 * 1000); |
| 580 | fs.utimesSync(oldZip, pastTime, pastTime); |
| 581 | |
| 582 | const freshZip = path.join(ZIP_CACHE_DIR, 'fresh.zip'); |
| 583 | fs.writeFileSync(freshZip, 'fake fresh zip'); |
| 584 | |
| 585 | pruneZipCache(); |
| 586 | |
| 587 | expect(fs.existsSync(oldZip)).toBe(false); |
| 588 | expect(fs.existsSync(freshZip)).toBe(true); |
| 589 | |
| 590 | // Cleanup |
| 591 | try { fs.unlinkSync(freshZip); } catch { /* ignore */ } |
| 592 | }); |
| 593 | }); |
| 594 | |
| 595 | describe('purgeExpiredShareTokens', () => |
| 596 | { |
| 597 | test('deletes expired share tokens and keeps valid ones', () => |
| 598 | { |
| 599 | const { purgeExpiredShareTokens } = require('../server/routes/share'); |
| 600 | const db = getDb(); |
| 601 | const now = Date.now(); |
| 602 | |
| 603 | db.prepare( |
| 604 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 605 | ).run(['expired-token', '/tmp/old.txt', 0, 'testuser', now - 10000, now - 1000]); |
| 606 | |
| 607 | db.prepare( |
| 608 | 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)', |
| 609 | ).run(['active-token', '/tmp/new.txt', 0, 'testuser', now - 1000, now + 60000]); |
| 610 | |
| 611 | const removed = purgeExpiredShareTokens({ nowMs: now }); |
| 612 | expect(removed).toBeGreaterThanOrEqual(1); |
| 613 | |
| 614 | const remaining = db.prepare('SELECT token FROM share_tokens ORDER BY token').all().map((row) => row.token); |
| 615 | expect(remaining).toContain('active-token'); |
| 616 | expect(remaining).not.toContain('expired-token'); |
| 617 | }); |
| 618 | }); |
| 619 | |
| 620 | // --------------------------------------------------------------------------- |
| 621 | // buildShareOpenGraphPage |
| 622 | // --------------------------------------------------------------------------- |
| 623 | describe('buildShareOpenGraphPage', () => |
| 624 | { |
| 625 | const { buildShareOpenGraphPage } = require('../server/routes/share'); |
| 626 | |
| 627 | const mockReq = { |
| 628 | protocol: 'https', |
| 629 | get: (header) => |
| 630 | { |
| 631 | if (header === 'host') return 'example.com'; |
| 632 | return null; |
| 633 | }, |
| 634 | }; |
| 635 | |
| 636 | function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 }) |
| 637 | { |
| 638 | getDb() |
| 639 | .prepare('INSERT OR REPLACE INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)') |
| 640 | .run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]); |
| 641 | } |
| 642 | |
| 643 | test('returns HTML page containing correct og:title for a valid file token', () => |
| 644 | { |
| 645 | insertToken({ token: 'og-valid', filePath: '/data/report.pdf' }); |
| 646 | const html = buildShareOpenGraphPage('og-valid', mockReq); |
| 647 | expect(html).toContain('<meta property="og:title" content="report.pdf"'); |
| 648 | expect(html).toContain('<title>report.pdf</title>'); |
| 649 | }); |
| 650 | |
| 651 | test('includes og:image and summary_large_image twitter:card for image files', () => |
| 652 | { |
| 653 | insertToken({ token: 'og-img', filePath: '/data/photo.jpg' }); |
| 654 | const html = buildShareOpenGraphPage('og-img', mockReq); |
| 655 | expect(html).toContain('property="og:image"'); |
| 656 | expect(html).toContain('/api/share/preview/og-img'); |
| 657 | expect(html).toContain('summary_large_image'); |
| 658 | }); |
| 659 | |
| 660 | test('includes og:image for png files', () => |
| 661 | { |
| 662 | insertToken({ token: 'og-png', filePath: '/data/banner.png' }); |
| 663 | const html = buildShareOpenGraphPage('og-png', mockReq); |
| 664 | expect(html).toContain('property="og:image"'); |
| 665 | }); |
| 666 | |
| 667 | test('includes og:image for webp files', () => |
| 668 | { |
| 669 | insertToken({ token: 'og-webp', filePath: '/data/thumb.webp' }); |
| 670 | const html = buildShareOpenGraphPage('og-webp', mockReq); |
| 671 | expect(html).toContain('property="og:image"'); |
| 672 | }); |
| 673 | |
| 674 | test('does not include og:image for non-image files and uses summary twitter:card', () => |
| 675 | { |
| 676 | insertToken({ token: 'og-video', filePath: '/data/movie.mkv' }); |
| 677 | const html = buildShareOpenGraphPage('og-video', mockReq); |
| 678 | expect(html).not.toContain('property="og:image"'); |
| 679 | expect(html).toContain('content="summary"'); |
| 680 | }); |
| 681 | |
| 682 | test('does not include og:image for directory tokens', () => |
| 683 | { |
| 684 | insertToken({ token: 'og-dir', filePath: '/data/photos', isDir: 1 }); |
| 685 | const html = buildShareOpenGraphPage('og-dir', mockReq); |
| 686 | expect(html).not.toContain('property="og:image"'); |
| 687 | }); |
| 688 | |
| 689 | test('returns "Link Expired" in og:title for an expired token', () => |
| 690 | { |
| 691 | insertToken({ token: 'og-exp', filePath: '/data/old.jpg', expiresAt: Date.now() - 1000 }); |
| 692 | const html = buildShareOpenGraphPage('og-exp', mockReq); |
| 693 | expect(html).toContain('content="Link Expired"'); |
| 694 | expect(html).not.toContain('property="og:image"'); |
| 695 | }); |
| 696 | |
| 697 | test('returns "Link Not Found" in og:title for an unknown token', () => |
| 698 | { |
| 699 | const html = buildShareOpenGraphPage('does-not-exist', mockReq); |
| 700 | expect(html).toContain('content="Link Not Found"'); |
| 701 | }); |
| 702 | |
| 703 | test('includes og:url pointing to the share page', () => |
| 704 | { |
| 705 | insertToken({ token: 'og-url', filePath: '/data/file.txt' }); |
| 706 | const html = buildShareOpenGraphPage('og-url', mockReq); |
| 707 | expect(html).toContain('https://example.com/share/og-url'); |
| 708 | }); |
| 709 | |
| 710 | test('og:description mentions validity for a valid token', () => |
| 711 | { |
| 712 | insertToken({ token: 'og-desc', filePath: '/data/doc.pdf', expiresAt: Date.now() + 7200000 }); |
| 713 | const html = buildShareOpenGraphPage('og-desc', mockReq); |
| 714 | expect(html).toContain('Valid for'); |
| 715 | }); |
| 716 | |
| 717 | test('retains the full share page client JS (not a bare meta-only response)', () => |
| 718 | { |
| 719 | insertToken({ token: 'og-full', filePath: '/data/file.txt' }); |
| 720 | const html = buildShareOpenGraphPage('og-full', mockReq); |
| 721 | // The interactive share page JS should still be present. |
| 722 | expect(html).toContain('api/share/info/'); |
| 723 | }); |
| 724 | }); |