| 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 | |
| 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 users ( |
| 26 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 27 | username TEXT UNIQUE NOT NULL, |
| 28 | password_hash TEXT NOT NULL, |
| 29 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 30 | permissions TEXT NOT NULL DEFAULT '{}' |
| 31 | ); |
| 32 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 33 | file_path TEXT PRIMARY KEY, |
| 34 | uploader TEXT NOT NULL DEFAULT '', |
| 35 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 36 | ); |
| 37 | `); |
| 38 | } |
| 39 | return db; |
| 40 | } |
| 41 | return { getDb, initDb: getDb }; |
| 42 | }); |
| 43 | |
| 44 | jest.mock('../server/config', () => ({ |
| 45 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }), |
| 46 | saveConfig: (config) => |
| 47 | { |
| 48 | mockPaths = [...(config.paths || [])]; |
| 49 | mockRootAliases = { ...(config.rootAliases || {}) }; |
| 50 | }, |
| 51 | getEffectivePaths: (paths) => paths, |
| 52 | getAllowedRoot: (targetPath, roots) => |
| 53 | { |
| 54 | const path = require('path'); |
| 55 | const absTarget = path.resolve(String(targetPath || '')); |
| 56 | return roots.find((root) => |
| 57 | { |
| 58 | const absRoot = path.resolve(root); |
| 59 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 60 | }) || null; |
| 61 | }, |
| 62 | })); |
| 63 | |
| 64 | jest.mock('../server/auth', () => ({ |
| 65 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 66 | })); |
| 67 | |
| 68 | jest.mock('../server/thumbnail-cache', () => ({ |
| 69 | getCachedThumbnailInfo: async () => |
| 70 | { |
| 71 | if (!mockThumbPath) return null; |
| 72 | return { thumbPath: mockThumbPath, contentType: 'image/webp' }; |
| 73 | }, |
| 74 | })); |
| 75 | |
| 76 | const filesRoutes = require('../server/routes/files'); |
| 77 | const { getDb } = require('../server/db'); |
| 78 | |
| 79 | let server; |
| 80 | let baseUrl; |
| 81 | let rootDir; |
| 82 | |
| 83 | beforeAll(async () => |
| 84 | { |
| 85 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 86 | mockPaths = [rootDir]; |
| 87 | |
| 88 | const app = express(); |
| 89 | app.use(express.json()); |
| 90 | app.use('/api/files', filesRoutes); |
| 91 | app.use((err, req, res, next) => |
| 92 | { |
| 93 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 94 | }); |
| 95 | |
| 96 | server = http.createServer(app); |
| 97 | server.listen(0); |
| 98 | await once(server, 'listening'); |
| 99 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 100 | }); |
| 101 | |
| 102 | afterAll(() => |
| 103 | { |
| 104 | server.close(); |
| 105 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 106 | }); |
| 107 | |
| 108 | beforeEach(() => |
| 109 | { |
| 110 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 111 | fs.mkdirSync(rootDir, { recursive: true }); |
| 112 | mockRootAliases = {}; |
| 113 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 114 | mockThumbPath = null; |
| 115 | const db = getDb(); |
| 116 | db.prepare('DELETE FROM file_meta').run([]); |
| 117 | db.prepare('DELETE FROM users').run([]); |
| 118 | }); |
| 119 | |
| 120 | function req (method, routePath, body) |
| 121 | { |
| 122 | const payload = body ? JSON.stringify(body) : undefined; |
| 123 | return new Promise((resolve, reject) => |
| 124 | { |
| 125 | const request = http.request(baseUrl + routePath, { |
| 126 | method, |
| 127 | headers: { |
| 128 | 'Content-Type': 'application/json', |
| 129 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 130 | }, |
| 131 | }, res => |
| 132 | { |
| 133 | let data = ''; |
| 134 | res.on('data', chunk => data += chunk); |
| 135 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 136 | }); |
| 137 | request.on('error', reject); |
| 138 | if (payload) request.write(payload); |
| 139 | request.end(); |
| 140 | }); |
| 141 | } |
| 142 | |
| 143 | function reqRaw (method, routePath) |
| 144 | { |
| 145 | return new Promise((resolve, reject) => |
| 146 | { |
| 147 | const request = http.request(baseUrl + routePath, { method }, res => |
| 148 | { |
| 149 | const chunks = []; |
| 150 | res.on('data', chunk => chunks.push(Buffer.from(chunk))); |
| 151 | res.on('end', () => resolve({ |
| 152 | status: res.statusCode, |
| 153 | headers: res.headers, |
| 154 | body: Buffer.concat(chunks), |
| 155 | })); |
| 156 | }); |
| 157 | request.on('error', reject); |
| 158 | request.end(); |
| 159 | }); |
| 160 | } |
| 161 | |
| 162 | describe('POST /api/files/move', () => |
| 163 | { |
| 164 | test('moves a file into another folder and rewrites metadata', async () => |
| 165 | { |
| 166 | const from = path.join(rootDir, 'alpha.txt'); |
| 167 | const toDir = path.join(rootDir, 'folder'); |
| 168 | fs.writeFileSync(from, 'hello'); |
| 169 | fs.mkdirSync(toDir); |
| 170 | |
| 171 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 172 | .run([from, 'admin', '["alice"]']); |
| 173 | |
| 174 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 175 | |
| 176 | expect(status).toBe(200); |
| 177 | expect(body.ok).toBe(true); |
| 178 | expect(fs.existsSync(from)).toBe(false); |
| 179 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 180 | |
| 181 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 182 | expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); |
| 183 | }); |
| 184 | |
| 185 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 186 | { |
| 187 | const fromDir = path.join(rootDir, 'src-folder'); |
| 188 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 189 | const toDir = path.join(rootDir, 'dest-folder'); |
| 190 | fs.mkdirSync(fromDir); |
| 191 | fs.mkdirSync(toDir); |
| 192 | fs.writeFileSync(nestedFile, 'hello'); |
| 193 | |
| 194 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 195 | .run([nestedFile, 'admin', '[]']); |
| 196 | |
| 197 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 198 | |
| 199 | expect(status).toBe(200); |
| 200 | expect(fs.existsSync(fromDir)).toBe(false); |
| 201 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 202 | |
| 203 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 204 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 205 | expect(movedMeta).toBeTruthy(); |
| 206 | }); |
| 207 | |
| 208 | test('rejects moving a folder into itself', async () => |
| 209 | { |
| 210 | const fromDir = path.join(rootDir, 'src-folder'); |
| 211 | const childDir = path.join(fromDir, 'child'); |
| 212 | fs.mkdirSync(childDir, { recursive: true }); |
| 213 | |
| 214 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 215 | |
| 216 | expect(status).toBe(400); |
| 217 | expect(body.error).toMatch(/folder into itself/i); |
| 218 | }); |
| 219 | }); |
| 220 | |
| 221 | describe('root alias endpoints', () => |
| 222 | { |
| 223 | test('GET /api/files/roots returns alias label and original name', async () => |
| 224 | { |
| 225 | mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; |
| 226 | |
| 227 | const { status, body } = await req('GET', '/api/files/roots'); |
| 228 | |
| 229 | expect(status).toBe(200); |
| 230 | expect(body.roots).toHaveLength(1); |
| 231 | expect(body.roots[0]).toMatchObject({ |
| 232 | path: rootDir, |
| 233 | label: 'Workspace', |
| 234 | alias: 'Workspace', |
| 235 | originalName: path.basename(rootDir), |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => |
| 240 | { |
| 241 | const originalBase = path.basename(rootDir); |
| 242 | const { status, body } = await req('POST', '/api/files/root-alias', { |
| 243 | rootPath: rootDir, |
| 244 | alias: 'Shared Files', |
| 245 | }); |
| 246 | |
| 247 | expect(status).toBe(200); |
| 248 | expect(body.ok).toBe(true); |
| 249 | expect(body.root).toMatchObject({ |
| 250 | path: rootDir, |
| 251 | label: 'Shared Files', |
| 252 | alias: 'Shared Files', |
| 253 | originalName: originalBase, |
| 254 | }); |
| 255 | expect(fs.existsSync(rootDir)).toBe(true); |
| 256 | |
| 257 | const afterRoots = await req('GET', '/api/files/roots'); |
| 258 | expect(afterRoots.status).toBe(200); |
| 259 | expect(afterRoots.body.roots[0].label).toBe('Shared Files'); |
| 260 | expect(afterRoots.body.roots[0].originalName).toBe(originalBase); |
| 261 | }); |
| 262 | |
| 263 | test('POST /api/files/root-alias rejects non-root paths', async () => |
| 264 | { |
| 265 | const nested = path.join(rootDir, 'sub'); |
| 266 | fs.mkdirSync(nested, { recursive: true }); |
| 267 | |
| 268 | const { status } = await req('POST', '/api/files/root-alias', { |
| 269 | rootPath: nested, |
| 270 | alias: 'Nested', |
| 271 | }); |
| 272 | |
| 273 | expect(status).toBe(400); |
| 274 | }); |
| 275 | }); |
| 276 | |
| 277 | describe('GET /api/files/thumbnail', () => |
| 278 | { |
| 279 | test('returns 404 while cached thumbnail is not ready', async () => |
| 280 | { |
| 281 | const source = path.join(rootDir, 'photo.jpg'); |
| 282 | fs.writeFileSync(source, 'not-an-image'); |
| 283 | |
| 284 | const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 285 | expect(status).toBe(404); |
| 286 | expect(body.error).toMatch(/not ready/i); |
| 287 | }); |
| 288 | |
| 289 | test('serves cached thumbnail file when available', async () => |
| 290 | { |
| 291 | const source = path.join(rootDir, 'photo.jpg'); |
| 292 | const thumb = path.join(rootDir, 'photo-thumb.webp'); |
| 293 | fs.writeFileSync(source, 'not-an-image'); |
| 294 | fs.writeFileSync(thumb, 'webp-bytes'); |
| 295 | mockThumbPath = thumb; |
| 296 | |
| 297 | const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 298 | expect(response.status).toBe(200); |
| 299 | expect(String(response.headers['content-type'] || '')).toContain('image/webp'); |
| 300 | expect(response.body.toString('utf8')).toBe('webp-bytes'); |
| 301 | }); |
| 302 | }); |
| 303 | |
| 304 | describe('GET /api/files/root-access', () => |
| 305 | { |
| 306 | test('returns users with R/R+W modes for an exact root path', async () => |
| 307 | { |
| 308 | const label = path.basename(rootDir); |
| 309 | const db = getDb(); |
| 310 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 311 | .run(['admin', 'x', 1, '{}']); |
| 312 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 313 | .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]); |
| 314 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 315 | .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]); |
| 316 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 317 | .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]); |
| 318 | |
| 319 | const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`); |
| 320 | expect(status).toBe(200); |
| 321 | expect(body.root).toMatchObject({ path: rootDir, originalName: label }); |
| 322 | expect(body.users).toEqual([ |
| 323 | { username: 'admin', mode: 'R+W' }, |
| 324 | { username: 'bob', mode: 'R+W' }, |
| 325 | { username: 'alice', mode: 'R' }, |
| 326 | ]); |
| 327 | }); |
| 328 | |
| 329 | test('rejects non-exact nested root paths', async () => |
| 330 | { |
| 331 | const nested = path.join(rootDir, 'sub'); |
| 332 | fs.mkdirSync(nested, { recursive: true }); |
| 333 | |
| 334 | const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`); |
| 335 | expect(status).toBe(400); |
| 336 | }); |
| 337 | }); |