BlueGit

timfa filemanager

Fix My Folder access paths

timfa Tim Falken · pushed by timfa

Authored 2026-05-14 · 6 months ago

Hash
7c87f490e877f7a28bc6eb4e388f925ee41bafd3
Parent
9d801ff9
9 files changed +217 −18
.github/technical-reference.md +7 −2
@@ -69,6 +69,7 @@
69 69 - splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
70 70 - pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
71 71 - removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
72 - movePathWithFallback(from, dest) - Moves files/folders with an EXDEV copy-then-delete fallback so cross-device moves into My Folder still succeed.
72 73 - POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
73 74 - POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
74 75 - POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
@@ -77,7 +78,10 @@
77 78 - POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
78 79
79 80 ## server/routes/share.js
80 - POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
81 - getUserFolderPath(config, username) - Resolves the owning user's personal folder path from config.userPath.
82 - resolveRootForUser(absPath, roots, user, config) - Resolves configured roots plus the owning user's personal folder for share checks.
83 - canReadInfo(user, info) - Read-check helper that always allows the owner of a personal folder root.
84 - POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt} and accepts items inside the authenticated user's My Folder.
81 85 - GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
82 86 - GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
83 87 - GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
@@ -181,7 +185,7 @@
181 185 - openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
182 186 - moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
183 187 - copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
184 - rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
188 - rootPermissionLabel(root) - Resolves permission key for a root using originalName when available; personal folders resolve to the built-in My Folder label.
185 189 - ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
186 190 - createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
187 191 - loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
@@ -190,6 +194,7 @@
190 194 - attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
191 195 - openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
192 196 - openSidebar(item) - Personal user roots display access as private and skip /files/root-access lookups to avoid forbidden noise.
197 - canWrite(item) - Resolves whether the current user may write to the selected item/root; personal folders are always writable for the owner.
193 198 - fetchRootAccessList(rootPath) - Fetches root access users from the server for a specific configured root.
194 199 - formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
195 200 - openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
@@ -69,6 +69,7 @@
69- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
69- splitNameExt(name) - Splits a filename into stem/ext, preserving dotless names and hidden-file behavior.
70- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
70- pickNumberedPath(dir, requestedName) - Finds the first free `name (n).ext` path inside a directory.
71- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
71- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
72- movePathWithFallback(from, dest) - Moves files/folders with an EXDEV copy-then-delete fallback so cross-device moves into My Folder still succeed.
72- POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
73- POST /api/files/upload - Streams multipart uploads into hidden temp files, computes/stores sha256, and enforces user-folder size limits.
73- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
74- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
74- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
75- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
@@ -77,7 +78,10 @@
77- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
78- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
78
79
79## server/routes/share.js
80## server/routes/share.js
80- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
81- getUserFolderPath(config, username) - Resolves the owning user's personal folder path from config.userPath.
82- resolveRootForUser(absPath, roots, user, config) - Resolves configured roots plus the owning user's personal folder for share checks.
83- canReadInfo(user, info) - Read-check helper that always allows the owner of a personal folder root.
84- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt} and accepts items inside the authenticated user's My Folder.
81- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
85- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
82- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
86- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
83- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
87- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
@@ -181,7 +185,7 @@
181- openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
185- openDestinationPicker(item, mode) - Shared destination picker state/labels for move vs copy operations.
182- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
186- moveWithConflictResolution(item, targetDir) - Attempts move and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
183- copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
187- copyWithConflictResolution(item, targetDir) - Attempts copy and handles 409 conflicts by prompting overwrite/rename/cancel then retries.
184- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
188- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available; personal folders resolve to the built-in My Folder label.
185- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
189- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
186- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
190- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
187- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
191- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
@@ -190,6 +194,7 @@
190- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
194- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
191- openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
195- openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
192- openSidebar(item) - Personal user roots display access as private and skip /files/root-access lookups to avoid forbidden noise.
196- openSidebar(item) - Personal user roots display access as private and skip /files/root-access lookups to avoid forbidden noise.
197- canWrite(item) - Resolves whether the current user may write to the selected item/root; personal folders are always writable for the owner.
193- fetchRootAccessList(rootPath) - Fetches root access users from the server for a specific configured root.
198- fetchRootAccessList(rootPath) - Fetches root access users from the server for a specific configured root.
194- formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
199- formatRootAccessList(users) - Formats root access entries as "username mode" values for sidebar rendering.
195- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
200- openSidebar(item) - Renders item details/actions in sidebar; root selections include alias/original name/usage/access list and keep Rename while hiding Move To/Delete.
.github/tests.md +1 −0
@@ -46,6 +46,7 @@
46 46 - `folder icon endpoints`
47 47 - `GET /api/files/download-zip`
48 48 - `video streaming routes`
49 - `SHA-256 hashing and duplicate detection`
49 50
50 51 ---
51 52
@@ -46,6 +46,7 @@
46- `folder icon endpoints`
46- `folder icon endpoints`
47- `GET /api/files/download-zip`
47- `GET /api/files/download-zip`
48- `video streaming routes`
48- `video streaming routes`
49- `SHA-256 hashing and duplicate detection`
49
50
50---
51---
51
52
public/app.js +2 −0
@@ -2082,6 +2082,7 @@ function formatRootAccessList (users)
2082 2082
2083 2083 function rootPermissionLabel (root)
2084 2084 {
2085 if (root && root.isUserFolder) return 'My Folder';
2085 2086 return (root && (root.originalName || root.label)) || '';
2086 2087 }
2087 2088
@@ -3414,6 +3415,7 @@ function canWrite (item = null)
3414 3415 ? item._root
3415 3416 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
3416 3417 if (!root) return false;
3418 if (root.isUserFolder) return true;
3417 3419 const p = STATE.permissions[rootPermissionLabel(root)];
3418 3420 return p && p.write;
3419 3421 }
@@ -2082,6 +2082,7 @@ function formatRootAccessList (users)
2082
2082
2083function rootPermissionLabel (root)
2083function rootPermissionLabel (root)
2084{
2084{
2085 if (root && root.isUserFolder) return 'My Folder';
2085 return (root && (root.originalName || root.label)) || '';
2086 return (root && (root.originalName || root.label)) || '';
2086}
2087}
2087
2088
@@ -3414,6 +3415,7 @@ function canWrite (item = null)
3414 ? item._root
3415 ? item._root
3415 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
3416 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
3416 if (!root) return false;
3417 if (!root) return false;
3418 if (root.isUserFolder) return true;
3417 const p = STATE.permissions[rootPermissionLabel(root)];
3419 const p = STATE.permissions[rootPermissionLabel(root)];
3418 return p && p.write;
3420 return p && p.write;
3419}
3421}
public/style.css +5 −0
@@ -518,6 +518,11 @@ button.danger:hover {
518 518 z-index: 11000;
519 519 }
520 520
521 #file-conflict-modal,
522 #overwrite-modal {
523 z-index: 11150;
524 }
525
521 526 .modal {
522 527 background: var(--surface);
523 528 border: 1px solid var(--border);
@@ -518,6 +518,11 @@ button.danger:hover {
518 z-index: 11000;
518 z-index: 11000;
519}
519}
520
520
521#file-conflict-modal,
522#overwrite-modal {
523 z-index: 11150;
524}
525
521.modal {
526.modal {
522 background: var(--surface);
527 background: var(--surface);
523 border: 1px solid var(--border);
528 border: 1px solid var(--border);
server/routes/files.js +29 −2
@@ -508,6 +508,33 @@ function removePathRecursive (targetPath)
508 508 }
509 509 }
510 510
511 function movePathWithFallback (from, dest)
512 {
513 const stat = fs.lstatSync(from);
514 try
515 {
516 fs.renameSync(from, dest);
517 return 'rename';
518 } catch (err)
519 {
520 try
521 {
522 if (stat.isDirectory())
523 {
524 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
525 } else
526 {
527 fs.copyFileSync(from, dest);
528 }
529 fs.rmSync(from, { recursive: true, force: true });
530 return 'copy-delete';
531 } catch (fallbackErr)
532 {
533 throw fallbackErr || err;
534 }
535 }
536 }
537
511 538 // ---------------------------------------------------------------------------
512 539 // GET /api/files/roots
513 540 // Returns the effective configured paths the user can read.
@@ -1213,7 +1240,7 @@ router.post('/rename', requireAuth, (req, res) =>
1213 1240
1214 1241 try
1215 1242 {
1216 fs.renameSync(from, dest);
1243 movePathWithFallback(from, dest);
1217 1244 } catch (err)
1218 1245 {
1219 1246 return res.status(500).json({ error: err.message });
@@ -1324,7 +1351,7 @@ router.post('/move', requireAuth, (req, res) =>
1324 1351
1325 1352 try
1326 1353 {
1327 fs.renameSync(from, dest);
1354 movePathWithFallback(from, dest);
1328 1355 } catch (err)
1329 1356 {
1330 1357 return res.status(500).json({ error: err.message });
@@ -508,6 +508,33 @@ function removePathRecursive (targetPath)
508 }
508 }
509}
509}
510
510
511function movePathWithFallback (from, dest)
512{
513 const stat = fs.lstatSync(from);
514 try
515 {
516 fs.renameSync(from, dest);
517 return 'rename';
518 } catch (err)
519 {
520 try
521 {
522 if (stat.isDirectory())
523 {
524 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
525 } else
526 {
527 fs.copyFileSync(from, dest);
528 }
529 fs.rmSync(from, { recursive: true, force: true });
530 return 'copy-delete';
531 } catch (fallbackErr)
532 {
533 throw fallbackErr || err;
534 }
535 }
536}
537
511// ---------------------------------------------------------------------------
538// ---------------------------------------------------------------------------
512// GET /api/files/roots
539// GET /api/files/roots
513// Returns the effective configured paths the user can read.
540// Returns the effective configured paths the user can read.
@@ -1213,7 +1240,7 @@ router.post('/rename', requireAuth, (req, res) =>
1213
1240
1214 try
1241 try
1215 {
1242 {
1216 fs.renameSync(from, dest);
1243 movePathWithFallback(from, dest);
1217 } catch (err)
1244 } catch (err)
1218 {
1245 {
1219 return res.status(500).json({ error: err.message });
1246 return res.status(500).json({ error: err.message });
@@ -1324,7 +1351,7 @@ router.post('/move', requireAuth, (req, res) =>
1324
1351
1325 try
1352 try
1326 {
1353 {
1327 fs.renameSync(from, dest);
1354 movePathWithFallback(from, dest);
1328 } catch (err)
1355 } catch (err)
1329 {
1356 {
1330 return res.status(500).json({ error: err.message });
1357 return res.status(500).json({ error: err.message });
server/routes/share.js +39 −12
@@ -31,6 +31,40 @@ function resolveRoot (absPath)
31 31 return getAllowedRoot(absPath, effectivePaths());
32 32 }
33 33
34 function getUserFolderPath (config, username)
35 {
36 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
37 if (!base) return null;
38 return path.join(base, String(username));
39 }
40
41 function resolveRootForUser (absPath, roots, user, config)
42 {
43 const matched = getAllowedRoot(absPath, roots);
44 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
45
46 if (!user || !user.username) return null;
47 const userFolder = getUserFolderPath(config, user.username);
48 if (!userFolder) return null;
49
50 const resolved = path.resolve(absPath);
51 const resolvedFolder = path.resolve(userFolder);
52 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
53 {
54 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
55 }
56
57 return null;
58 }
59
60 function canReadInfo (user, info)
61 {
62 if (!info) return false;
63 if (info.isUserFolder) return true;
64 if (user.isAdmin) return true;
65 return !!(user.permissions[info.label] && user.permissions[info.label].read);
66 }
67
34 68 /** Generate a cryptographically random token. */
35 69 function generateToken ()
36 70 {
@@ -151,18 +185,10 @@ router.post('/create', requireAuth, (req, res) =>
151 185 return res.status(400).json({ error: 'filePath is required.' });
152 186 }
153 187
154 const root = resolveRoot(filePath);
155 if (!root)
156 {
157 return res.status(403).json({ error: 'Access denied.' });
158 }
159
160 // Verify the user can read that root.
161 const rootLabel = path.basename(root);
162 const user = req.user;
163 const canRead = user.isAdmin
164 || !!(user.permissions[rootLabel] && user.permissions[rootLabel].read);
165 if (!canRead)
188 const config = loadConfig();
189 const roots = effectivePaths();
190 const info = resolveRootForUser(filePath, roots, req.user, config);
191 if (!info || !canReadInfo(req.user, info))
166 192 {
167 193 return res.status(403).json({ error: 'Access denied.' });
168 194 }
@@ -180,6 +206,7 @@ router.post('/create', requireAuth, (req, res) =>
180 206 const now = Date.now();
181 207 const expiresAt = now + SHARE_TTL_MS;
182 208 const token = generateToken();
209 const user = req.user;
183 210
184 211 const db = getDb();
185 212 db.prepare(`
@@ -31,6 +31,40 @@ function resolveRoot (absPath)
31 return getAllowedRoot(absPath, effectivePaths());
31 return getAllowedRoot(absPath, effectivePaths());
32}
32}
33
33
34function getUserFolderPath (config, username)
35{
36 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
37 if (!base) return null;
38 return path.join(base, String(username));
39}
40
41function resolveRootForUser (absPath, roots, user, config)
42{
43 const matched = getAllowedRoot(absPath, roots);
44 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
45
46 if (!user || !user.username) return null;
47 const userFolder = getUserFolderPath(config, user.username);
48 if (!userFolder) return null;
49
50 const resolved = path.resolve(absPath);
51 const resolvedFolder = path.resolve(userFolder);
52 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
53 {
54 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
55 }
56
57 return null;
58}
59
60function canReadInfo (user, info)
61{
62 if (!info) return false;
63 if (info.isUserFolder) return true;
64 if (user.isAdmin) return true;
65 return !!(user.permissions[info.label] && user.permissions[info.label].read);
66}
67
34/** Generate a cryptographically random token. */
68/** Generate a cryptographically random token. */
35function generateToken ()
69function generateToken ()
36{
70{
@@ -151,18 +185,10 @@ router.post('/create', requireAuth, (req, res) =>
151 return res.status(400).json({ error: 'filePath is required.' });
185 return res.status(400).json({ error: 'filePath is required.' });
152 }
186 }
153
187
154 const root = resolveRoot(filePath);
188 const config = loadConfig();
155 if (!root)
189 const roots = effectivePaths();
156 {
190 const info = resolveRootForUser(filePath, roots, req.user, config);
157 return res.status(403).json({ error: 'Access denied.' });
191 if (!info || !canReadInfo(req.user, info))
158 }
159
160 // Verify the user can read that root.
161 const rootLabel = path.basename(root);
162 const user = req.user;
163 const canRead = user.isAdmin
164 || !!(user.permissions[rootLabel] && user.permissions[rootLabel].read);
165 if (!canRead)
166 {
192 {
167 return res.status(403).json({ error: 'Access denied.' });
193 return res.status(403).json({ error: 'Access denied.' });
168 }
194 }
@@ -180,6 +206,7 @@ router.post('/create', requireAuth, (req, res) =>
180 const now = Date.now();
206 const now = Date.now();
181 const expiresAt = now + SHARE_TTL_MS;
207 const expiresAt = now + SHARE_TTL_MS;
182 const token = generateToken();
208 const token = generateToken();
209 const user = req.user;
183
210
184 const db = getDb();
211 const db = getDb();
185 db.prepare(`
212 db.prepare(`
tests/files.routes.test.js +50 −1
@@ -8,6 +8,7 @@ const path = require('path');
8 8 const { once } = require('events');
9 9
10 10 let mockPaths = [];
11 let mockUserPath = null;
11 12 let mockRootAliases = {};
12 13 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13 14 let mockThumbPath = null;
@@ -51,7 +52,7 @@ jest.mock('../server/db', () =>
51 52 });
52 53
53 54 jest.mock('../server/config', () => ({
54 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
55 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
55 56 saveConfig: (config) =>
56 57 {
57 58 mockPaths = [...(config.paths || [])];
@@ -146,7 +147,13 @@ beforeEach(() =>
146 147 {
147 148 fs.rmSync(rootDir, { recursive: true, force: true });
148 149 fs.mkdirSync(rootDir, { recursive: true });
150 if (mockUserPath)
151 {
152 fs.rmSync(mockUserPath, { recursive: true, force: true });
153 fs.mkdirSync(mockUserPath, { recursive: true });
154 }
149 155 mockRootAliases = {};
156 mockUserPath = null;
150 157 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
151 158 mockThumbPath = null;
152 159 mockFolderImages = [];
@@ -422,6 +429,48 @@ describe('POST /api/files/move', () =>
422 429 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
423 430 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
424 431 });
432
433 test('moves a file into My Folder when rename falls back across filesystems', async () =>
434 {
435 const sourceFile = path.join(rootDir, 'cross-root.txt');
436 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
437 const userFolder = path.join(userFolderBase, 'alice');
438
439 mockPaths = [rootDir];
440 mockUserPath = userFolderBase;
441 mockUser = {
442 username: 'alice',
443 isAdmin: false,
444 permissions: {
445 [path.basename(rootDir)]: { read: true, write: true },
446 },
447 };
448
449 fs.writeFileSync(sourceFile, 'hello');
450 fs.mkdirSync(userFolder, { recursive: true });
451
452 const originalRenameSync = fs.renameSync;
453 fs.renameSync = (from, to) =>
454 {
455 const err = new Error('cross-device move');
456 err.code = 'EXDEV';
457 throw err;
458 };
459
460 try
461 {
462 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
463
464 expect(status).toBe(200);
465 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
466 expect(fs.existsSync(sourceFile)).toBe(false);
467 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
468 } finally
469 {
470 fs.renameSync = originalRenameSync;
471 fs.rmSync(userFolderBase, { recursive: true, force: true });
472 }
473 });
425 474 });
426 475
427 476 describe('root alias endpoints', () =>
@@ -8,6 +8,7 @@ const path = require('path');
8const { once } = require('events');
8const { once } = require('events');
9
9
10let mockPaths = [];
10let mockPaths = [];
11let mockUserPath = null;
11let mockRootAliases = {};
12let mockRootAliases = {};
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
13let mockThumbPath = null;
14let mockThumbPath = null;
@@ -51,7 +52,7 @@ jest.mock('../server/db', () =>
51});
52});
52
53
53jest.mock('../server/config', () => ({
54jest.mock('../server/config', () => ({
54 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
55 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
55 saveConfig: (config) =>
56 saveConfig: (config) =>
56 {
57 {
57 mockPaths = [...(config.paths || [])];
58 mockPaths = [...(config.paths || [])];
@@ -146,7 +147,13 @@ beforeEach(() =>
146{
147{
147 fs.rmSync(rootDir, { recursive: true, force: true });
148 fs.rmSync(rootDir, { recursive: true, force: true });
148 fs.mkdirSync(rootDir, { recursive: true });
149 fs.mkdirSync(rootDir, { recursive: true });
150 if (mockUserPath)
151 {
152 fs.rmSync(mockUserPath, { recursive: true, force: true });
153 fs.mkdirSync(mockUserPath, { recursive: true });
154 }
149 mockRootAliases = {};
155 mockRootAliases = {};
156 mockUserPath = null;
150 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
157 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
151 mockThumbPath = null;
158 mockThumbPath = null;
152 mockFolderImages = [];
159 mockFolderImages = [];
@@ -422,6 +429,48 @@ describe('POST /api/files/move', () =>
422 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
429 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
423 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
430 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
424 });
431 });
432
433 test('moves a file into My Folder when rename falls back across filesystems', async () =>
434 {
435 const sourceFile = path.join(rootDir, 'cross-root.txt');
436 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
437 const userFolder = path.join(userFolderBase, 'alice');
438
439 mockPaths = [rootDir];
440 mockUserPath = userFolderBase;
441 mockUser = {
442 username: 'alice',
443 isAdmin: false,
444 permissions: {
445 [path.basename(rootDir)]: { read: true, write: true },
446 },
447 };
448
449 fs.writeFileSync(sourceFile, 'hello');
450 fs.mkdirSync(userFolder, { recursive: true });
451
452 const originalRenameSync = fs.renameSync;
453 fs.renameSync = (from, to) =>
454 {
455 const err = new Error('cross-device move');
456 err.code = 'EXDEV';
457 throw err;
458 };
459
460 try
461 {
462 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
463
464 expect(status).toBe(200);
465 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
466 expect(fs.existsSync(sourceFile)).toBe(false);
467 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
468 } finally
469 {
470 fs.renameSync = originalRenameSync;
471 fs.rmSync(userFolderBase, { recursive: true, force: true });
472 }
473 });
425});
474});
426
475
427describe('root alias endpoints', () =>
476describe('root alias endpoints', () =>
tests/page.load.test.js +53 −0
@@ -584,6 +584,59 @@ describe('page load smoke test', () =>
584 584 dom.window.close();
585 585 });
586 586
587 test('files inside My Folder still expose write actions to the owner', async () =>
588 {
589 const myFolderPath = '/personal/tester';
590 rootsFixture = [
591 { label: 'My Folder', path: myFolderPath, originalName: 'tester', alias: 'My Folder', isUserFolder: true },
592 { label: 'Root', path: '/data', originalName: 'data', alias: null },
593 ];
594 listFixture = {
595 [myFolderPath]: [
596 {
597 name: 'private.txt',
598 path: `${myFolderPath}/private.txt`,
599 isDir: false,
600 size: 3,
601 mtime: Date.now(),
602 },
603 ],
604 };
605 meFixture = {
606 username: 'tester',
607 isAdmin: false,
608 permissions: {},
609 };
610
611 const { dom, runtimeErrors } = await bootClient({
612 savedSession: {
613 token: 'saved-token',
614 dir: null,
615 rootPath: null,
616 lastOperationAt: Date.now(),
617 },
618 });
619
620 expect(runtimeErrors).toEqual([]);
621 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/personal/tester"]'));
622
623 const rootTile = dom.window.document.querySelector('.file-item[data-path="/personal/tester"]');
624 rootTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
625 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/personal/tester/private.txt"]'));
626
627 const fileTile = dom.window.document.querySelector('.file-item[data-path="/personal/tester/private.txt"]');
628 fileTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
629 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
630
631 const actionButtons = Array.from(dom.window.document.querySelectorAll('#sidebar-actions button')).map(b => b.textContent);
632 expect(actionButtons).toContain('Share');
633 expect(actionButtons).toContain('Move to');
634 expect(actionButtons).toContain('Copy to');
635 expect(actionButtons).toContain('Rename');
636
637 dom.window.close();
638 });
639
587 640 test('base-level root sidebar shows access list with no item selected', async () =>
588 641 {
589 642 rootAccessFixture = {
@@ -584,6 +584,59 @@ describe('page load smoke test', () =>
584 dom.window.close();
584 dom.window.close();
585 });
585 });
586
586
587 test('files inside My Folder still expose write actions to the owner', async () =>
588 {
589 const myFolderPath = '/personal/tester';
590 rootsFixture = [
591 { label: 'My Folder', path: myFolderPath, originalName: 'tester', alias: 'My Folder', isUserFolder: true },
592 { label: 'Root', path: '/data', originalName: 'data', alias: null },
593 ];
594 listFixture = {
595 [myFolderPath]: [
596 {
597 name: 'private.txt',
598 path: `${myFolderPath}/private.txt`,
599 isDir: false,
600 size: 3,
601 mtime: Date.now(),
602 },
603 ],
604 };
605 meFixture = {
606 username: 'tester',
607 isAdmin: false,
608 permissions: {},
609 };
610
611 const { dom, runtimeErrors } = await bootClient({
612 savedSession: {
613 token: 'saved-token',
614 dir: null,
615 rootPath: null,
616 lastOperationAt: Date.now(),
617 },
618 });
619
620 expect(runtimeErrors).toEqual([]);
621 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/personal/tester"]'));
622
623 const rootTile = dom.window.document.querySelector('.file-item[data-path="/personal/tester"]');
624 rootTile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
625 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/personal/tester/private.txt"]'));
626
627 const fileTile = dom.window.document.querySelector('.file-item[data-path="/personal/tester/private.txt"]');
628 fileTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
629 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
630
631 const actionButtons = Array.from(dom.window.document.querySelectorAll('#sidebar-actions button')).map(b => b.textContent);
632 expect(actionButtons).toContain('Share');
633 expect(actionButtons).toContain('Move to');
634 expect(actionButtons).toContain('Copy to');
635 expect(actionButtons).toContain('Rename');
636
637 dom.window.close();
638 });
639
587 test('base-level root sidebar shows access list with no item selected', async () =>
640 test('base-level root sidebar shows access list with no item selected', async () =>
588 {
641 {
589 rootAccessFixture = {
642 rootAccessFixture = {
tests/share.routes.test.js +31 −1
@@ -8,6 +8,7 @@ const path = require('path');
8 8 const { once } = require('events');
9 9
10 10 let mockPaths = [];
11 let mockUserPath = null;
11 12 let mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
12 13 let mockVideoStreamSession = null;
13 14 let mockVideoStreamAsset = null;
@@ -38,7 +39,7 @@ jest.mock('../server/db', () =>
38 39 });
39 40
40 41 jest.mock('../server/config', () => ({
41 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: {} }),
42 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: {} }),
42 43 saveConfig: jest.fn(),
43 44 getEffectivePaths: (paths) => paths,
44 45 getAllowedRoot: (targetPath, roots) =>
@@ -119,6 +120,12 @@ beforeEach(() =>
119 120 {
120 121 fs.rmSync(rootDir, { recursive: true, force: true });
121 122 fs.mkdirSync(rootDir, { recursive: true });
123 if (mockUserPath)
124 {
125 fs.rmSync(mockUserPath, { recursive: true, force: true });
126 fs.mkdirSync(mockUserPath, { recursive: true });
127 }
128 mockUserPath = null;
122 129 mockVideoStreamSession = null;
123 130 mockVideoStreamAsset = null;
124 131 // Reset DB between tests
@@ -173,6 +180,29 @@ describe('POST /api/share/create', () =>
173 180 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
174 181 expect(res.status).toBe(404);
175 182 });
183
184 test('creates a token for a file inside My Folder', async () =>
185 {
186 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-userfolders-'));
187 const userFolder = path.join(userFolderBase, 'testuser');
188 const filePath = path.join(userFolder, 'private.txt');
189
190 mockUserPath = userFolderBase;
191 mockUser = { username: 'testuser', isAdmin: false, permissions: {} };
192 fs.mkdirSync(userFolder, { recursive: true });
193 fs.writeFileSync(filePath, 'private');
194
195 try
196 {
197 const res = await post('/api/share/create', { filePath });
198 expect(res.status).toBe(200);
199 const body = await res.json();
200 expect(typeof body.token).toBe('string');
201 } finally
202 {
203 fs.rmSync(userFolderBase, { recursive: true, force: true });
204 }
205 });
176 206 });
177 207
178 208 // ---------------------------------------------------------------------------
@@ -8,6 +8,7 @@ const path = require('path');
8const { once } = require('events');
8const { once } = require('events');
9
9
10let mockPaths = [];
10let mockPaths = [];
11let mockUserPath = null;
11let mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
12let mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
12let mockVideoStreamSession = null;
13let mockVideoStreamSession = null;
13let mockVideoStreamAsset = null;
14let mockVideoStreamAsset = null;
@@ -38,7 +39,7 @@ jest.mock('../server/db', () =>
38});
39});
39
40
40jest.mock('../server/config', () => ({
41jest.mock('../server/config', () => ({
41 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: {} }),
42 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: {} }),
42 saveConfig: jest.fn(),
43 saveConfig: jest.fn(),
43 getEffectivePaths: (paths) => paths,
44 getEffectivePaths: (paths) => paths,
44 getAllowedRoot: (targetPath, roots) =>
45 getAllowedRoot: (targetPath, roots) =>
@@ -119,6 +120,12 @@ beforeEach(() =>
119{
120{
120 fs.rmSync(rootDir, { recursive: true, force: true });
121 fs.rmSync(rootDir, { recursive: true, force: true });
121 fs.mkdirSync(rootDir, { recursive: true });
122 fs.mkdirSync(rootDir, { recursive: true });
123 if (mockUserPath)
124 {
125 fs.rmSync(mockUserPath, { recursive: true, force: true });
126 fs.mkdirSync(mockUserPath, { recursive: true });
127 }
128 mockUserPath = null;
122 mockVideoStreamSession = null;
129 mockVideoStreamSession = null;
123 mockVideoStreamAsset = null;
130 mockVideoStreamAsset = null;
124 // Reset DB between tests
131 // Reset DB between tests
@@ -173,6 +180,29 @@ describe('POST /api/share/create', () =>
173 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
180 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
174 expect(res.status).toBe(404);
181 expect(res.status).toBe(404);
175 });
182 });
183
184 test('creates a token for a file inside My Folder', async () =>
185 {
186 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-userfolders-'));
187 const userFolder = path.join(userFolderBase, 'testuser');
188 const filePath = path.join(userFolder, 'private.txt');
189
190 mockUserPath = userFolderBase;
191 mockUser = { username: 'testuser', isAdmin: false, permissions: {} };
192 fs.mkdirSync(userFolder, { recursive: true });
193 fs.writeFileSync(filePath, 'private');
194
195 try
196 {
197 const res = await post('/api/share/create', { filePath });
198 expect(res.status).toBe(200);
199 const body = await res.json();
200 expect(typeof body.token).toBe('string');
201 } finally
202 {
203 fs.rmSync(userFolderBase, { recursive: true, force: true });
204 }
205 });
176});
206});
177
207
178// ---------------------------------------------------------------------------
208// ---------------------------------------------------------------------------