Add POST /api/files/move endpoint with metadata rewrite and tests
@@ -122,6 +122,44 @@ function resolveRoot (absPath, roots)
122
122
return { root: matchedRoot, label: path.basename(matchedRoot) };
123
123
}
124
124
125
function sameResolvedPath (a, b)
126
{
127
return path.resolve(String(a || '')) === path.resolve(String(b || ''));
128
}
129
130
function pathInsideResolved (child, root)
131
{
132
const relative = path.relative(path.resolve(root), path.resolve(child));
133
return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
134
}
135
136
function rewriteMetaPaths (fromPath, toPath)
137
{
138
const db = getDb();
139
const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
140
.all([fromPath, fromPath + path.sep + '%']);
141
142
if (!rows.length) return;
143
144
const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
145
const upsert = db.prepare(`
146
INSERT INTO file_meta (file_path, uploader, downloaders)
147
VALUES (?, ?, ?)
148
ON CONFLICT(file_path) DO UPDATE SET
149
uploader = excluded.uploader,
150
downloaders = excluded.downloaders
151
`);
152
153
for (const row of rows)
154
{
155
const nextPath = row.file_path === fromPath
156
? toPath
157
: toPath + row.file_path.slice(fromPath.length);
158
del.run([row.file_path]);
159
upsert.run([nextPath, row.uploader, row.downloaders]);
160
}
161
}
162
125
163
// ---------------------------------------------------------------------------
126
164
// GET /api/files/roots
127
165
// Returns the effective configured paths the user can read.
@@ -390,13 +428,66 @@ router.post('/rename', requireAuth, (req, res) =>
390
428
return res.status(500).json({ error: err.message });
391
429
}
392
430
393
// Update DB meta key
394
const db = getDb();
395
db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
431
rewriteMetaPaths(from, dest);
396
432
397
433
res.json({ ok: true });
398
434
});
399
435
436
// ---------------------------------------------------------------------------
437
// POST /api/files/move
438
// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
439
// ---------------------------------------------------------------------------
440
router.post('/move', requireAuth, (req, res) =>
441
{
442
const { from, toDir } = req.body;
443
if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
444
445
const roots = effectivePaths();
446
const fromInfo = resolveRoot(from, roots);
447
const toInfo = resolveRoot(toDir, roots);
448
if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
449
if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
450
{
451
return res.status(403).json({ error: 'Access denied.' });
452
}
453
454
let sourceStat;
455
let destStat;
456
try
457
{
458
sourceStat = fs.statSync(from);
459
destStat = fs.statSync(toDir);
460
} catch
461
{
462
return res.status(404).json({ error: 'Source or destination not found.' });
463
}
464
465
if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
466
467
const dest = path.join(toDir, path.basename(from));
468
if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
469
if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
470
{
471
return res.status(400).json({ error: 'Cannot move onto itself.' });
472
}
473
if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
474
{
475
return res.status(400).json({ error: 'Cannot move a folder into itself.' });
476
}
477
if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
478
479
try
480
{
481
fs.renameSync(from, dest);
482
} catch (err)
483
{
484
return res.status(500).json({ error: err.message });
485
}
486
487
rewriteMetaPaths(from, dest);
488
res.json({ ok: true, path: dest });
489
});
490
400
491
// ---------------------------------------------------------------------------
401
492
// POST /api/files/mkdir
402
493
// Body: { dir: <absolute-path>, name: <folder-name> }
@@ -122,6 +122,44 @@ function resolveRoot (absPath, roots)122
return { root: matchedRoot, label: path.basename(matchedRoot) };122
return { root: matchedRoot, label: path.basename(matchedRoot) };123
}123
}124
124
125
function sameResolvedPath (a, b)126
{127
return path.resolve(String(a || '')) === path.resolve(String(b || ''));128
}129
130
function pathInsideResolved (child, root)131
{132
const relative = path.relative(path.resolve(root), path.resolve(child));133
return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);134
}135
136
function rewriteMetaPaths (fromPath, toPath)137
{138
const db = getDb();139
const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')140
.all([fromPath, fromPath + path.sep + '%']);141
142
if (!rows.length) return;143
144
const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');145
const upsert = db.prepare(`146
INSERT INTO file_meta (file_path, uploader, downloaders)147
VALUES (?, ?, ?)148
ON CONFLICT(file_path) DO UPDATE SET149
uploader = excluded.uploader,150
downloaders = excluded.downloaders151
`);152
153
for (const row of rows)154
{155
const nextPath = row.file_path === fromPath156
? toPath157
: toPath + row.file_path.slice(fromPath.length);158
del.run([row.file_path]);159
upsert.run([nextPath, row.uploader, row.downloaders]);160
}161
}162
125
// ---------------------------------------------------------------------------163
// ---------------------------------------------------------------------------126
// GET /api/files/roots164
// GET /api/files/roots127
// Returns the effective configured paths the user can read.165
// Returns the effective configured paths the user can read.@@ -390,13 +428,66 @@ router.post('/rename', requireAuth, (req, res) =>390
return res.status(500).json({ error: err.message });428
return res.status(500).json({ error: err.message });391
}429
}392
430
393
// Update DB meta key431
rewriteMetaPaths(from, dest);394
const db = getDb();395
db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);396
432
397
res.json({ ok: true });433
res.json({ ok: true });398
});434
});399
435
436
// ---------------------------------------------------------------------------437
// POST /api/files/move438
// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }439
// ---------------------------------------------------------------------------440
router.post('/move', requireAuth, (req, res) =>441
{442
const { from, toDir } = req.body;443
if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });444
445
const roots = effectivePaths();446
const fromInfo = resolveRoot(from, roots);447
const toInfo = resolveRoot(toDir, roots);448
if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });449
if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))450
{451
return res.status(403).json({ error: 'Access denied.' });452
}453
454
let sourceStat;455
let destStat;456
try457
{458
sourceStat = fs.statSync(from);459
destStat = fs.statSync(toDir);460
} catch461
{462
return res.status(404).json({ error: 'Source or destination not found.' });463
}464
465
if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });466
467
const dest = path.join(toDir, path.basename(from));468
if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });469
if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))470
{471
return res.status(400).json({ error: 'Cannot move onto itself.' });472
}473
if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))474
{475
return res.status(400).json({ error: 'Cannot move a folder into itself.' });476
}477
if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });478
479
try480
{481
fs.renameSync(from, dest);482
} catch (err)483
{484
return res.status(500).json({ error: err.message });485
}486
487
rewriteMetaPaths(from, dest);488
res.json({ ok: true, path: dest });489
});490
400
// ---------------------------------------------------------------------------491
// ---------------------------------------------------------------------------401
// POST /api/files/mkdir492
// POST /api/files/mkdir402
// Body: { dir: <absolute-path>, name: <folder-name> }493
// Body: { dir: <absolute-path>, name: <folder-name> }@@ -0,0 +1,174 @@
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
});
@@ -0,0 +1,174 @@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
});