| 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 | |
| 14 | jest.mock('../server/db', () => |
| 15 | { |
| 16 | const { Database } = require('node-sqlite3-wasm'); |
| 17 | let db; |
| 18 | function getDb () |
| 19 | { |
| 20 | if (!db) |
| 21 | { |
| 22 | db = new Database(':memory:'); |
| 23 | db.exec(` |
| 24 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 25 | file_path TEXT PRIMARY KEY, |
| 26 | uploader TEXT NOT NULL DEFAULT '', |
| 27 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 28 | ); |
| 29 | `); |
| 30 | } |
| 31 | return db; |
| 32 | } |
| 33 | return { getDb, initDb: getDb }; |
| 34 | }); |
| 35 | |
| 36 | jest.mock('../server/config', () => ({ |
| 37 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }), |
| 38 | saveConfig: (config) => |
| 39 | { |
| 40 | mockPaths = [...(config.paths || [])]; |
| 41 | mockRootAliases = { ...(config.rootAliases || {}) }; |
| 42 | }, |
| 43 | getEffectivePaths: (paths) => paths, |
| 44 | getAllowedRoot: (targetPath, roots) => |
| 45 | { |
| 46 | const path = require('path'); |
| 47 | const absTarget = path.resolve(String(targetPath || '')); |
| 48 | return roots.find((root) => |
| 49 | { |
| 50 | const absRoot = path.resolve(root); |
| 51 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 52 | }) || null; |
| 53 | }, |
| 54 | })); |
| 55 | |
| 56 | jest.mock('../server/auth', () => ({ |
| 57 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 58 | })); |
| 59 | |
| 60 | const filesRoutes = require('../server/routes/files'); |
| 61 | const { getDb } = require('../server/db'); |
| 62 | |
| 63 | let server; |
| 64 | let baseUrl; |
| 65 | let rootDir; |
| 66 | |
| 67 | beforeAll(async () => |
| 68 | { |
| 69 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 70 | mockPaths = [rootDir]; |
| 71 | |
| 72 | const app = express(); |
| 73 | app.use(express.json()); |
| 74 | app.use('/api/files', filesRoutes); |
| 75 | app.use((err, req, res, next) => |
| 76 | { |
| 77 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 78 | }); |
| 79 | |
| 80 | server = http.createServer(app); |
| 81 | server.listen(0); |
| 82 | await once(server, 'listening'); |
| 83 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 84 | }); |
| 85 | |
| 86 | afterAll(() => |
| 87 | { |
| 88 | server.close(); |
| 89 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 90 | }); |
| 91 | |
| 92 | beforeEach(() => |
| 93 | { |
| 94 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 95 | fs.mkdirSync(rootDir, { recursive: true }); |
| 96 | mockRootAliases = {}; |
| 97 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 98 | const db = getDb(); |
| 99 | db.prepare('DELETE FROM file_meta').run([]); |
| 100 | }); |
| 101 | |
| 102 | function req (method, routePath, body) |
| 103 | { |
| 104 | const payload = body ? JSON.stringify(body) : undefined; |
| 105 | return new Promise((resolve, reject) => |
| 106 | { |
| 107 | const request = http.request(baseUrl + routePath, { |
| 108 | method, |
| 109 | headers: { |
| 110 | 'Content-Type': 'application/json', |
| 111 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 112 | }, |
| 113 | }, res => |
| 114 | { |
| 115 | let data = ''; |
| 116 | res.on('data', chunk => data += chunk); |
| 117 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 118 | }); |
| 119 | request.on('error', reject); |
| 120 | if (payload) request.write(payload); |
| 121 | request.end(); |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | describe('POST /api/files/move', () => |
| 126 | { |
| 127 | test('moves a file into another folder and rewrites metadata', async () => |
| 128 | { |
| 129 | const from = path.join(rootDir, 'alpha.txt'); |
| 130 | const toDir = path.join(rootDir, 'folder'); |
| 131 | fs.writeFileSync(from, 'hello'); |
| 132 | fs.mkdirSync(toDir); |
| 133 | |
| 134 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 135 | .run([from, 'admin', '["alice"]']); |
| 136 | |
| 137 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 138 | |
| 139 | expect(status).toBe(200); |
| 140 | expect(body.ok).toBe(true); |
| 141 | expect(fs.existsSync(from)).toBe(false); |
| 142 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 143 | |
| 144 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 145 | expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); |
| 146 | }); |
| 147 | |
| 148 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 149 | { |
| 150 | const fromDir = path.join(rootDir, 'src-folder'); |
| 151 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 152 | const toDir = path.join(rootDir, 'dest-folder'); |
| 153 | fs.mkdirSync(fromDir); |
| 154 | fs.mkdirSync(toDir); |
| 155 | fs.writeFileSync(nestedFile, 'hello'); |
| 156 | |
| 157 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 158 | .run([nestedFile, 'admin', '[]']); |
| 159 | |
| 160 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 161 | |
| 162 | expect(status).toBe(200); |
| 163 | expect(fs.existsSync(fromDir)).toBe(false); |
| 164 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 165 | |
| 166 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 167 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 168 | expect(movedMeta).toBeTruthy(); |
| 169 | }); |
| 170 | |
| 171 | test('rejects moving a folder into itself', async () => |
| 172 | { |
| 173 | const fromDir = path.join(rootDir, 'src-folder'); |
| 174 | const childDir = path.join(fromDir, 'child'); |
| 175 | fs.mkdirSync(childDir, { recursive: true }); |
| 176 | |
| 177 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 178 | |
| 179 | expect(status).toBe(400); |
| 180 | expect(body.error).toMatch(/folder into itself/i); |
| 181 | }); |
| 182 | }); |
| 183 | |
| 184 | describe('root alias endpoints', () => |
| 185 | { |
| 186 | test('GET /api/files/roots returns alias label and original name', async () => |
| 187 | { |
| 188 | mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; |
| 189 | |
| 190 | const { status, body } = await req('GET', '/api/files/roots'); |
| 191 | |
| 192 | expect(status).toBe(200); |
| 193 | expect(body.roots).toHaveLength(1); |
| 194 | expect(body.roots[0]).toMatchObject({ |
| 195 | path: rootDir, |
| 196 | label: 'Workspace', |
| 197 | alias: 'Workspace', |
| 198 | originalName: path.basename(rootDir), |
| 199 | }); |
| 200 | }); |
| 201 | |
| 202 | test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => |
| 203 | { |
| 204 | const originalBase = path.basename(rootDir); |
| 205 | const { status, body } = await req('POST', '/api/files/root-alias', { |
| 206 | rootPath: rootDir, |
| 207 | alias: 'Shared Files', |
| 208 | }); |
| 209 | |
| 210 | expect(status).toBe(200); |
| 211 | expect(body.ok).toBe(true); |
| 212 | expect(body.root).toMatchObject({ |
| 213 | path: rootDir, |
| 214 | label: 'Shared Files', |
| 215 | alias: 'Shared Files', |
| 216 | originalName: originalBase, |
| 217 | }); |
| 218 | expect(fs.existsSync(rootDir)).toBe(true); |
| 219 | |
| 220 | const afterRoots = await req('GET', '/api/files/roots'); |
| 221 | expect(afterRoots.status).toBe(200); |
| 222 | expect(afterRoots.body.roots[0].label).toBe('Shared Files'); |
| 223 | expect(afterRoots.body.roots[0].originalName).toBe(originalBase); |
| 224 | }); |
| 225 | |
| 226 | test('POST /api/files/root-alias rejects non-root paths', async () => |
| 227 | { |
| 228 | const nested = path.join(rootDir, 'sub'); |
| 229 | fs.mkdirSync(nested, { recursive: true }); |
| 230 | |
| 231 | const { status } = await req('POST', '/api/files/root-alias', { |
| 232 | rootPath: nested, |
| 233 | alias: 'Nested', |
| 234 | }); |
| 235 | |
| 236 | expect(status).toBe(400); |
| 237 | }); |
| 238 | }); |