| 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: 'admin', isAdmin: true, permissions: {} }; |
| 12 | |
| 13 | jest.mock('../server/db', () => |
| 14 | { |
| 15 | const { Database } = require('node-sqlite3-wasm'); |
| 16 | let db; |
| 17 | function getDb () |
| 18 | { |
| 19 | if (!db) |
| 20 | { |
| 21 | db = new Database(':memory:'); |
| 22 | db.exec(` |
| 23 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 24 | file_path TEXT PRIMARY KEY, |
| 25 | uploader TEXT NOT NULL DEFAULT '', |
| 26 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 27 | ); |
| 28 | `); |
| 29 | } |
| 30 | return db; |
| 31 | } |
| 32 | return { getDb, initDb: getDb }; |
| 33 | }); |
| 34 | |
| 35 | jest.mock('../server/config', () => ({ |
| 36 | loadConfig: () => ({ port: 3000, paths: [...mockPaths] }), |
| 37 | getEffectivePaths: (paths) => paths, |
| 38 | getAllowedRoot: (targetPath, roots) => |
| 39 | { |
| 40 | const path = require('path'); |
| 41 | const absTarget = path.resolve(String(targetPath || '')); |
| 42 | return roots.find((root) => |
| 43 | { |
| 44 | const absRoot = path.resolve(root); |
| 45 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 46 | }) || null; |
| 47 | }, |
| 48 | })); |
| 49 | |
| 50 | jest.mock('../server/auth', () => ({ |
| 51 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 52 | })); |
| 53 | |
| 54 | const filesRoutes = require('../server/routes/files'); |
| 55 | const { getDb } = require('../server/db'); |
| 56 | |
| 57 | let server; |
| 58 | let baseUrl; |
| 59 | let rootDir; |
| 60 | |
| 61 | beforeAll(async () => |
| 62 | { |
| 63 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 64 | mockPaths = [rootDir]; |
| 65 | |
| 66 | const app = express(); |
| 67 | app.use(express.json()); |
| 68 | app.use('/api/files', filesRoutes); |
| 69 | app.use((err, req, res, next) => |
| 70 | { |
| 71 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 72 | }); |
| 73 | |
| 74 | server = http.createServer(app); |
| 75 | server.listen(0); |
| 76 | await once(server, 'listening'); |
| 77 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 78 | }); |
| 79 | |
| 80 | afterAll(() => |
| 81 | { |
| 82 | server.close(); |
| 83 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 84 | }); |
| 85 | |
| 86 | beforeEach(() => |
| 87 | { |
| 88 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 89 | fs.mkdirSync(rootDir, { recursive: true }); |
| 90 | const db = getDb(); |
| 91 | db.prepare('DELETE FROM file_meta').run([]); |
| 92 | }); |
| 93 | |
| 94 | function req (method, routePath, body) |
| 95 | { |
| 96 | const payload = body ? JSON.stringify(body) : undefined; |
| 97 | return new Promise((resolve, reject) => |
| 98 | { |
| 99 | const request = http.request(baseUrl + routePath, { |
| 100 | method, |
| 101 | headers: { |
| 102 | 'Content-Type': 'application/json', |
| 103 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 104 | }, |
| 105 | }, res => |
| 106 | { |
| 107 | let data = ''; |
| 108 | res.on('data', chunk => data += chunk); |
| 109 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 110 | }); |
| 111 | request.on('error', reject); |
| 112 | if (payload) request.write(payload); |
| 113 | request.end(); |
| 114 | }); |
| 115 | } |
| 116 | |
| 117 | describe('POST /api/files/move', () => |
| 118 | { |
| 119 | test('moves a file into another folder and rewrites metadata', async () => |
| 120 | { |
| 121 | const from = path.join(rootDir, 'alpha.txt'); |
| 122 | const toDir = path.join(rootDir, 'folder'); |
| 123 | fs.writeFileSync(from, 'hello'); |
| 124 | fs.mkdirSync(toDir); |
| 125 | |
| 126 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 127 | .run([from, 'admin', '["alice"]']); |
| 128 | |
| 129 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 130 | |
| 131 | expect(status).toBe(200); |
| 132 | expect(body.ok).toBe(true); |
| 133 | expect(fs.existsSync(from)).toBe(false); |
| 134 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 135 | |
| 136 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 137 | expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); |
| 138 | }); |
| 139 | |
| 140 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 141 | { |
| 142 | const fromDir = path.join(rootDir, 'src-folder'); |
| 143 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 144 | const toDir = path.join(rootDir, 'dest-folder'); |
| 145 | fs.mkdirSync(fromDir); |
| 146 | fs.mkdirSync(toDir); |
| 147 | fs.writeFileSync(nestedFile, 'hello'); |
| 148 | |
| 149 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 150 | .run([nestedFile, 'admin', '[]']); |
| 151 | |
| 152 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 153 | |
| 154 | expect(status).toBe(200); |
| 155 | expect(fs.existsSync(fromDir)).toBe(false); |
| 156 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 157 | |
| 158 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 159 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 160 | expect(movedMeta).toBeTruthy(); |
| 161 | }); |
| 162 | |
| 163 | test('rejects moving a folder into itself', async () => |
| 164 | { |
| 165 | const fromDir = path.join(rootDir, 'src-folder'); |
| 166 | const childDir = path.join(fromDir, 'child'); |
| 167 | fs.mkdirSync(childDir, { recursive: true }); |
| 168 | |
| 169 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 170 | |
| 171 | expect(status).toBe(400); |
| 172 | expect(body.error).toMatch(/folder into itself/i); |
| 173 | }); |
| 174 | }); |