BlueGit

timfa filemanager

Handle orphaned userfolders in admin panel

timfa Tim Falken · pushed by timfa

Authored 2026-05-17 · 6 months ago

Hash
8fd0f82da8e61c089fe4e6b17a8033f26d7c7502
Parent
a2825cb9
10 files changed +467 −1
.github/technical-reference.md +6 −0
@@ -51,6 +51,8 @@
51 51 ## server/routes/admin.js
52 52 - POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
53 53 - PATCH /api/admin/users/:id - Updates user password/admin flag/permissions; rejects self-demotion and still blocks removing the last admin account.
54 - GET /api/admin/orphan-userfolders - Returns non-empty user folders under userPath that no longer match any account, and auto-deletes empty orphan folders.
55 - DELETE /api/admin/users/:id - Also removes the deleted user's personal folder when it exists and is empty.
54 56 - normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
55 57 - ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
56 58 - GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
@@ -62,6 +64,7 @@
62 64 - GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
63 65 - loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
64 66 - resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
67 - resolveRootForUser(absPath, roots, user, config) - Allows admins to access orphaned user folders (deleted-account folders) under userPath.
65 68 - canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
66 69 - checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
67 70 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
@@ -136,6 +139,7 @@
136 139 - Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
137 140 - Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
138 141 - Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
142 - Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
139 143 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
140 144 - Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
141 145
@@ -178,6 +182,7 @@
178 182 - openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
179 183 - openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
180 184 - refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
185 - refreshAdminOrphanUserFolders() - Fetches `/admin/orphan-userfolders`, conditionally renders orphaned folder rows, and wires "Open folder" navigation for admins.
181 186 - refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
182 187 - disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
183 188 - getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
@@ -246,6 +251,7 @@
246 251 - openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
247 252 - uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
248 253 - openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
254 - refreshAdminOrphanUserFolders() UI flow - Admin panel shows orphaned user folders only when present and opens selected orphan folder from the section button.
249 255
250 256 ## public/drag-move.js
251 257 - makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
@@ -51,6 +51,8 @@
51## server/routes/admin.js
51## server/routes/admin.js
52- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
52- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
53- PATCH /api/admin/users/:id - Updates user password/admin flag/permissions; rejects self-demotion and still blocks removing the last admin account.
53- PATCH /api/admin/users/:id - Updates user password/admin flag/permissions; rejects self-demotion and still blocks removing the last admin account.
54- GET /api/admin/orphan-userfolders - Returns non-empty user folders under userPath that no longer match any account, and auto-deletes empty orphan folders.
55- DELETE /api/admin/users/:id - Also removes the deleted user's personal folder when it exists and is empty.
54- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
56- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
55- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
57- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
56- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
58- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
@@ -62,6 +64,7 @@
62- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
64- GET /api/files/roots - Adds a synthetic 'My folder' root for the authenticated user when userPath is configured.
63- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
65- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
64- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
66- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
67- resolveRootForUser(absPath, roots, user, config) - Allows admins to access orphaned user folders (deleted-account folders) under userPath.
65- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
68- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
66- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
69- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
67- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
70- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
@@ -136,6 +139,7 @@
136- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
139- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
137- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
140- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
138- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
141- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
142- Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
139- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
143- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
140- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
144- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
141
145
@@ -178,6 +182,7 @@
178- openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
182- openIconPickerModal(options) - Shared icon-picker modal used by folder-icon and global-favicon flows; includes live thumbnail-name filtering.
179- openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
183- openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
180- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
184- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
185- refreshAdminOrphanUserFolders() - Fetches `/admin/orphan-userfolders`, conditionally renders orphaned folder rows, and wires "Open folder" navigation for admins.
181- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
186- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
182- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
187- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
183- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
188- getThumbnailKind(name) - Classifies files into image/text/badge thumbnail strategies.
@@ -246,6 +251,7 @@
246- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
251- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
247- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
252- uploadFiles(fileList) - Uploads files one-by-one with per-file conflict prompt (overwrite/rename/cancel) when names already exist.
248- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
253- openUserModal(user, paths) - Admin user editor; enforces UI permission rule that Write is disabled/unchecked while Read is unchecked and disables the Admin checkbox when editing the current signed-in admin account.
254- refreshAdminOrphanUserFolders() UI flow - Admin panel shows orphaned user folders only when present and opens selected orphan folder from the section button.
249
255
250## public/drag-move.js
256## public/drag-move.js
251- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
257- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
.github/tests.md +2 −0
@@ -10,6 +10,7 @@
10 10 - `POST /api/admin/users`
11 11 - `PATCH /api/admin/users/:id`
12 12 - `DELETE /api/admin/users/:id`
13 - `GET /api/admin/orphan-userfolders`
13 14 - `GET /api/admin/config`
14 15 - `PUT /api/admin/config`
15 16 - `POST /api/admin/shutdown`
@@ -43,6 +44,7 @@
43 44 - `root alias endpoints`
44 45 - `GET /api/files/thumbnail`
45 46 - `GET /api/files/root-access`
47 - `orphaned user folder access`
46 48 - `folder icon endpoints`
47 49 - `file search endpoint`
48 50 - `image search endpoint`
@@ -10,6 +10,7 @@
10- `POST /api/admin/users`
10- `POST /api/admin/users`
11- `PATCH /api/admin/users/:id`
11- `PATCH /api/admin/users/:id`
12- `DELETE /api/admin/users/:id`
12- `DELETE /api/admin/users/:id`
13- `GET /api/admin/orphan-userfolders`
13- `GET /api/admin/config`
14- `GET /api/admin/config`
14- `PUT /api/admin/config`
15- `PUT /api/admin/config`
15- `POST /api/admin/shutdown`
16- `POST /api/admin/shutdown`
@@ -43,6 +44,7 @@
43- `root alias endpoints`
44- `root alias endpoints`
44- `GET /api/files/thumbnail`
45- `GET /api/files/thumbnail`
45- `GET /api/files/root-access`
46- `GET /api/files/root-access`
47- `orphaned user folder access`
46- `folder icon endpoints`
48- `folder icon endpoints`
47- `file search endpoint`
49- `file search endpoint`
48- `image search endpoint`
50- `image search endpoint`
public/app.js +77 −0
@@ -5166,6 +5166,83 @@ async function refreshAdminUsers ()
5166 5166 });
5167 5167 container.appendChild(row);
5168 5168 }
5169
5170 await refreshAdminOrphanUserFolders();
5171 }
5172
5173 async function refreshAdminOrphanUserFolders ()
5174 {
5175 const section = document.getElementById('admin-orphan-userfolders-section');
5176 const list = document.getElementById('admin-orphan-userfolders-list');
5177 if (!section || !list) return;
5178
5179 let data = null;
5180 try
5181 {
5182 data = await api('GET', '/admin/orphan-userfolders');
5183 } catch
5184 {
5185 section.classList.add('hidden');
5186 list.innerHTML = '';
5187 return;
5188 }
5189
5190 const folders = Array.isArray(data && data.folders) ? data.folders : [];
5191 if (!folders.length)
5192 {
5193 section.classList.add('hidden');
5194 list.innerHTML = '';
5195 return;
5196 }
5197
5198 section.classList.remove('hidden');
5199 list.innerHTML = '';
5200
5201 for (const folder of folders)
5202 {
5203 const row = document.createElement('div');
5204 row.className = 'user-row orphan-folder-row';
5205
5206 const name = document.createElement('span');
5207 name.className = 'user-name';
5208 name.textContent = folder.folderName || 'Unknown folder';
5209
5210 const info = document.createElement('span');
5211 info.className = 'orphan-folder-meta';
5212 const itemCount = Number(folder.itemCount) || 0;
5213 info.textContent = `${itemCount} item${itemCount === 1 ? '' : 's'}`;
5214
5215 const openBtn = document.createElement('button');
5216 openBtn.dataset.action = 'open-orphan-folder';
5217 openBtn.textContent = 'Open folder';
5218 openBtn.addEventListener('click', async () =>
5219 {
5220 const targetPath = String(folder.path || '').trim();
5221 if (!targetPath) return;
5222
5223 try
5224 {
5225 const syntheticRoot = {
5226 label: name.textContent,
5227 originalName: name.textContent,
5228 alias: null,
5229 path: targetPath,
5230 isUserFolder: true,
5231 isOrphanUserFolder: true,
5232 };
5233 await navigateTo(targetPath, syntheticRoot);
5234 document.getElementById('admin-modal').classList.add('hidden');
5235 } catch (err)
5236 {
5237 toast(err.message || 'Failed to open folder.', 'err');
5238 }
5239 });
5240
5241 row.appendChild(name);
5242 row.appendChild(info);
5243 row.appendChild(openBtn);
5244 list.appendChild(row);
5245 }
5169 5246 }
5170 5247
5171 5248 async function refreshAdminUpdateStatus (opts = {})
@@ -5166,6 +5166,83 @@ async function refreshAdminUsers ()
5166 });
5166 });
5167 container.appendChild(row);
5167 container.appendChild(row);
5168 }
5168 }
5169
5170 await refreshAdminOrphanUserFolders();
5171}
5172
5173async function refreshAdminOrphanUserFolders ()
5174{
5175 const section = document.getElementById('admin-orphan-userfolders-section');
5176 const list = document.getElementById('admin-orphan-userfolders-list');
5177 if (!section || !list) return;
5178
5179 let data = null;
5180 try
5181 {
5182 data = await api('GET', '/admin/orphan-userfolders');
5183 } catch
5184 {
5185 section.classList.add('hidden');
5186 list.innerHTML = '';
5187 return;
5188 }
5189
5190 const folders = Array.isArray(data && data.folders) ? data.folders : [];
5191 if (!folders.length)
5192 {
5193 section.classList.add('hidden');
5194 list.innerHTML = '';
5195 return;
5196 }
5197
5198 section.classList.remove('hidden');
5199 list.innerHTML = '';
5200
5201 for (const folder of folders)
5202 {
5203 const row = document.createElement('div');
5204 row.className = 'user-row orphan-folder-row';
5205
5206 const name = document.createElement('span');
5207 name.className = 'user-name';
5208 name.textContent = folder.folderName || 'Unknown folder';
5209
5210 const info = document.createElement('span');
5211 info.className = 'orphan-folder-meta';
5212 const itemCount = Number(folder.itemCount) || 0;
5213 info.textContent = `${itemCount} item${itemCount === 1 ? '' : 's'}`;
5214
5215 const openBtn = document.createElement('button');
5216 openBtn.dataset.action = 'open-orphan-folder';
5217 openBtn.textContent = 'Open folder';
5218 openBtn.addEventListener('click', async () =>
5219 {
5220 const targetPath = String(folder.path || '').trim();
5221 if (!targetPath) return;
5222
5223 try
5224 {
5225 const syntheticRoot = {
5226 label: name.textContent,
5227 originalName: name.textContent,
5228 alias: null,
5229 path: targetPath,
5230 isUserFolder: true,
5231 isOrphanUserFolder: true,
5232 };
5233 await navigateTo(targetPath, syntheticRoot);
5234 document.getElementById('admin-modal').classList.add('hidden');
5235 } catch (err)
5236 {
5237 toast(err.message || 'Failed to open folder.', 'err');
5238 }
5239 });
5240
5241 row.appendChild(name);
5242 row.appendChild(info);
5243 row.appendChild(openBtn);
5244 list.appendChild(row);
5245 }
5169}
5246}
5170
5247
5171async function refreshAdminUpdateStatus (opts = {})
5248async function refreshAdminUpdateStatus (opts = {})
public/index.html +5 −0
@@ -181,6 +181,11 @@
181 181 <h3>Users</h3>
182 182 <div id="admin-users-list"></div>
183 183 <button id="admin-new-user-btn" class="primary">+ New user</button>
184 <div id="admin-orphan-userfolders-section" class="hidden">
185 <h4>Orphaned User Folders</h4>
186 <p class="muted">Folders without an existing account. Admins always have full read and write access.</p>
187 <div id="admin-orphan-userfolders-list"></div>
188 </div>
184 189 </section>
185 190
186 191 <section>
@@ -181,6 +181,11 @@
181 <h3>Users</h3>
181 <h3>Users</h3>
182 <div id="admin-users-list"></div>
182 <div id="admin-users-list"></div>
183 <button id="admin-new-user-btn" class="primary">+ New user</button>
183 <button id="admin-new-user-btn" class="primary">+ New user</button>
184 <div id="admin-orphan-userfolders-section" class="hidden">
185 <h4>Orphaned User Folders</h4>
186 <p class="muted">Folders without an existing account. Admins always have full read and write access.</p>
187 <div id="admin-orphan-userfolders-list"></div>
188 </div>
184 </section>
189 </section>
185
190
186 <section>
191 <section>
public/style.css +17 −0
@@ -951,6 +951,23 @@ button.danger.admin-update-highlight {
951 951 color: var(--danger);
952 952 }
953 953
954 #admin-orphan-userfolders-section {
955 margin-top: 1rem;
956 padding-top: 0.55rem;
957 border-top: 1px solid var(--border);
958 }
959
960 #admin-orphan-userfolders-section h4 {
961 margin: 0 0 0.35rem;
962 font-size: 0.86rem;
963 color: var(--text);
964 }
965
966 .orphan-folder-row .orphan-folder-meta {
967 font-size: 0.8rem;
968 color: var(--text-muted);
969 }
970
954 971 /* User form permissions */
955 972 #user-permissions {
956 973 margin-top: 0.75rem;
@@ -951,6 +951,23 @@ button.danger.admin-update-highlight {
951 color: var(--danger);
951 color: var(--danger);
952}
952}
953
953
954#admin-orphan-userfolders-section {
955 margin-top: 1rem;
956 padding-top: 0.55rem;
957 border-top: 1px solid var(--border);
958}
959
960#admin-orphan-userfolders-section h4 {
961 margin: 0 0 0.35rem;
962 font-size: 0.86rem;
963 color: var(--text);
964}
965
966.orphan-folder-row .orphan-folder-meta {
967 font-size: 0.8rem;
968 color: var(--text-muted);
969}
970
954/* User form permissions */
971/* User form permissions */
955#user-permissions {
972#user-permissions {
956 margin-top: 0.75rem;
973 margin-top: 0.75rem;
server/routes/admin.js +97 −0
@@ -65,6 +65,80 @@ function normalizePermissions (permissions)
65 65 return normalized;
66 66 }
67 67
68 function userFolderRootFromConfig (config)
69 {
70 const raw = config && typeof config.userPath === 'string' ? config.userPath.trim() : '';
71 return raw ? path.resolve(raw) : null;
72 }
73
74 function removeIfEmptyDir (dirPath)
75 {
76 try
77 {
78 const entries = fs.readdirSync(dirPath);
79 if (entries.length !== 0) return false;
80 fs.rmdirSync(dirPath);
81 return true;
82 } catch
83 {
84 return false;
85 }
86 }
87
88 function listOrphanUserFolders (userFolderRoot, options = {})
89 {
90 const deleteEmpty = !!options.deleteEmpty;
91 if (!userFolderRoot) return [];
92
93 let entries = [];
94 try
95 {
96 entries = fs.readdirSync(userFolderRoot, { withFileTypes: true });
97 } catch
98 {
99 return [];
100 }
101
102 const db = getDb();
103 const users = db.prepare('SELECT username FROM users').all();
104 const usernames = new Set(users.map((u) => String(u.username || '').toLowerCase()));
105
106 const out = [];
107 for (const entry of entries)
108 {
109 if (!entry.isDirectory()) continue;
110
111 const folderName = String(entry.name || '');
112 if (!folderName) continue;
113 if (usernames.has(folderName.toLowerCase())) continue;
114
115 const folderPath = path.join(userFolderRoot, folderName);
116 let itemCount = 0;
117 try
118 {
119 itemCount = fs.readdirSync(folderPath).length;
120 } catch
121 {
122 continue;
123 }
124
125 if (itemCount === 0 && deleteEmpty)
126 {
127 const removed = removeIfEmptyDir(folderPath);
128 if (removed) continue;
129 }
130
131 out.push({
132 folderName,
133 path: folderPath,
134 itemCount,
135 });
136 }
137
138 out.sort((a, b) => a.folderName.localeCompare(b.folderName));
139 return out;
140 }
141
68 142 // All admin routes require authentication + admin privilege
69 143 router.use(requireAuth, requireAdmin);
70 144
@@ -86,6 +160,19 @@ router.get('/users', (req, res) =>
86 160 });
87 161 });
88 162
163 // ---------------------------------------------------------------------------
164 // GET /api/admin/orphan-userfolders
165 // Returns non-empty user folders that are not linked to an existing user.
166 // Empty orphan folders are auto-deleted.
167 // ---------------------------------------------------------------------------
168 router.get('/orphan-userfolders', (req, res) =>
169 {
170 const config = loadConfig();
171 const userFolderRoot = userFolderRootFromConfig(config);
172 const folders = listOrphanUserFolders(userFolderRoot, { deleteEmpty: true });
173 res.json({ folders });
174 });
175
89 176 // ---------------------------------------------------------------------------
90 177 // POST /api/admin/users
91 178 // Body: { username, password, isAdmin, permissions }
@@ -196,6 +283,16 @@ router.delete('/users/:id', (req, res) =>
196 283 }
197 284
198 285 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
286
287 // If the deleted user's personal folder is now empty, remove it automatically.
288 const config = loadConfig();
289 const userFolderRoot = userFolderRootFromConfig(config);
290 if (userFolderRoot)
291 {
292 const folderPath = path.join(userFolderRoot, String(user.username || ''));
293 removeIfEmptyDir(folderPath);
294 }
295
199 296 res.json({ ok: true });
200 297 });
201 298
@@ -65,6 +65,80 @@ function normalizePermissions (permissions)
65 return normalized;
65 return normalized;
66}
66}
67
67
68function userFolderRootFromConfig (config)
69{
70 const raw = config && typeof config.userPath === 'string' ? config.userPath.trim() : '';
71 return raw ? path.resolve(raw) : null;
72}
73
74function removeIfEmptyDir (dirPath)
75{
76 try
77 {
78 const entries = fs.readdirSync(dirPath);
79 if (entries.length !== 0) return false;
80 fs.rmdirSync(dirPath);
81 return true;
82 } catch
83 {
84 return false;
85 }
86}
87
88function listOrphanUserFolders (userFolderRoot, options = {})
89{
90 const deleteEmpty = !!options.deleteEmpty;
91 if (!userFolderRoot) return [];
92
93 let entries = [];
94 try
95 {
96 entries = fs.readdirSync(userFolderRoot, { withFileTypes: true });
97 } catch
98 {
99 return [];
100 }
101
102 const db = getDb();
103 const users = db.prepare('SELECT username FROM users').all();
104 const usernames = new Set(users.map((u) => String(u.username || '').toLowerCase()));
105
106 const out = [];
107 for (const entry of entries)
108 {
109 if (!entry.isDirectory()) continue;
110
111 const folderName = String(entry.name || '');
112 if (!folderName) continue;
113 if (usernames.has(folderName.toLowerCase())) continue;
114
115 const folderPath = path.join(userFolderRoot, folderName);
116 let itemCount = 0;
117 try
118 {
119 itemCount = fs.readdirSync(folderPath).length;
120 } catch
121 {
122 continue;
123 }
124
125 if (itemCount === 0 && deleteEmpty)
126 {
127 const removed = removeIfEmptyDir(folderPath);
128 if (removed) continue;
129 }
130
131 out.push({
132 folderName,
133 path: folderPath,
134 itemCount,
135 });
136 }
137
138 out.sort((a, b) => a.folderName.localeCompare(b.folderName));
139 return out;
140}
141
68// All admin routes require authentication + admin privilege
142// All admin routes require authentication + admin privilege
69router.use(requireAuth, requireAdmin);
143router.use(requireAuth, requireAdmin);
70
144
@@ -86,6 +160,19 @@ router.get('/users', (req, res) =>
86 });
160 });
87});
161});
88
162
163// ---------------------------------------------------------------------------
164// GET /api/admin/orphan-userfolders
165// Returns non-empty user folders that are not linked to an existing user.
166// Empty orphan folders are auto-deleted.
167// ---------------------------------------------------------------------------
168router.get('/orphan-userfolders', (req, res) =>
169{
170 const config = loadConfig();
171 const userFolderRoot = userFolderRootFromConfig(config);
172 const folders = listOrphanUserFolders(userFolderRoot, { deleteEmpty: true });
173 res.json({ folders });
174});
175
89// ---------------------------------------------------------------------------
176// ---------------------------------------------------------------------------
90// POST /api/admin/users
177// POST /api/admin/users
91// Body: { username, password, isAdmin, permissions }
178// Body: { username, password, isAdmin, permissions }
@@ -196,6 +283,16 @@ router.delete('/users/:id', (req, res) =>
196 }
283 }
197
284
198 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
285 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
286
287 // If the deleted user's personal folder is now empty, remove it automatically.
288 const config = loadConfig();
289 const userFolderRoot = userFolderRootFromConfig(config);
290 if (userFolderRoot)
291 {
292 const folderPath = path.join(userFolderRoot, String(user.username || ''));
293 removeIfEmptyDir(folderPath);
294 }
295
199 res.json({ ok: true });
296 res.json({ ok: true });
200});
297});
201
298
server/routes/files.js +41 −0
@@ -537,6 +537,20 @@ function getUserFolderPath (config, username)
537 537 return path.join(base, String(username));
538 538 }
539 539
540 function getUserFolderRootPath (config)
541 {
542 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
543 if (!base) return null;
544 return path.resolve(base);
545 }
546
547 function existingUsernamesLowerSet ()
548 {
549 const db = getDb();
550 const rows = db.prepare('SELECT username FROM users').all();
551 return new Set(rows.map((row) => String(row.username || '').toLowerCase()));
552 }
553
540 554 /**
541 555 * Resolves a request path against both the configured roots AND the user's
542 556 * personal folder. Returns { root, label, isUserFolder } or null.
@@ -560,6 +574,31 @@ function resolveRootForUser (absPath, roots, user, config)
560 574 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
561 575 }
562 576
577 // Admins can access orphaned user folders (folders without a matching account).
578 if (user && user.isAdmin)
579 {
580 const userFolderRoot = getUserFolderRootPath(config);
581 if (!userFolderRoot) return null;
582
583 const relative = path.relative(userFolderRoot, resolved);
584 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
585
586 const parts = relative.split(path.sep).filter(Boolean);
587 if (!parts.length) return null;
588
589 const folderName = parts[0];
590 const usernames = existingUsernamesLowerSet();
591 if (usernames.has(String(folderName).toLowerCase())) return null;
592
593 const orphanRoot = path.join(userFolderRoot, folderName);
594 return {
595 root: orphanRoot,
596 label: folderName,
597 isUserFolder: false,
598 isOrphanUserFolder: true,
599 };
600 }
601
563 602 return null;
564 603 }
565 604
@@ -571,6 +610,7 @@ function canReadInfo (user, info)
571 610 {
572 611 if (!info) return false;
573 612 if (info.isUserFolder) return true; // owner always has full access
613 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
574 614 return canRead(user, info.label);
575 615 }
576 616
@@ -581,6 +621,7 @@ function canWriteInfo (user, info)
581 621 {
582 622 if (!info) return false;
583 623 if (info.isUserFolder) return true;
624 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
584 625 return canWrite(user, info.label);
585 626 }
586 627
@@ -537,6 +537,20 @@ function getUserFolderPath (config, username)
537 return path.join(base, String(username));
537 return path.join(base, String(username));
538}
538}
539
539
540function getUserFolderRootPath (config)
541{
542 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
543 if (!base) return null;
544 return path.resolve(base);
545}
546
547function existingUsernamesLowerSet ()
548{
549 const db = getDb();
550 const rows = db.prepare('SELECT username FROM users').all();
551 return new Set(rows.map((row) => String(row.username || '').toLowerCase()));
552}
553
540/**
554/**
541 * Resolves a request path against both the configured roots AND the user's
555 * Resolves a request path against both the configured roots AND the user's
542 * personal folder. Returns { root, label, isUserFolder } or null.
556 * personal folder. Returns { root, label, isUserFolder } or null.
@@ -560,6 +574,31 @@ function resolveRootForUser (absPath, roots, user, config)
560 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
574 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
561 }
575 }
562
576
577 // Admins can access orphaned user folders (folders without a matching account).
578 if (user && user.isAdmin)
579 {
580 const userFolderRoot = getUserFolderRootPath(config);
581 if (!userFolderRoot) return null;
582
583 const relative = path.relative(userFolderRoot, resolved);
584 if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
585
586 const parts = relative.split(path.sep).filter(Boolean);
587 if (!parts.length) return null;
588
589 const folderName = parts[0];
590 const usernames = existingUsernamesLowerSet();
591 if (usernames.has(String(folderName).toLowerCase())) return null;
592
593 const orphanRoot = path.join(userFolderRoot, folderName);
594 return {
595 root: orphanRoot,
596 label: folderName,
597 isUserFolder: false,
598 isOrphanUserFolder: true,
599 };
600 }
601
563 return null;
602 return null;
564}
603}
565
604
@@ -571,6 +610,7 @@ function canReadInfo (user, info)
571{
610{
572 if (!info) return false;
611 if (!info) return false;
573 if (info.isUserFolder) return true; // owner always has full access
612 if (info.isUserFolder) return true; // owner always has full access
613 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
574 return canRead(user, info.label);
614 return canRead(user, info.label);
575}
615}
576
616
@@ -581,6 +621,7 @@ function canWriteInfo (user, info)
581{
621{
582 if (!info) return false;
622 if (!info) return false;
583 if (info.isUserFolder) return true;
623 if (info.isUserFolder) return true;
624 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
584 return canWrite(user, info.label);
625 return canWrite(user, info.label);
585}
626}
586
627
tests/admin.routes.test.js +101 −1
@@ -8,6 +8,9 @@ const express = require('express');
8 8 const http = require('http');
9 9 const { once } = require('events');
10 10 const crypto = require('crypto');
11 const fs = require('fs');
12 const os = require('os');
13 const path = require('path');
11 14
12 15 // ── child_process mock — controlled per test ──────────────────────────────────
13 16 let mockExecFileImpl = null;
@@ -61,7 +64,7 @@ jest.mock('../server/db', () =>
61 64 });
62 65
63 66 // ── config mock ─────────────────────────────────────────────────────────────
64 const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
67 const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
65 68 jest.mock('../server/config', () => ({
66 69 loadConfig: () => ({ ...mockConfig }),
67 70 saveConfig: (c) => Object.assign(mockConfig, c),
@@ -296,6 +299,103 @@ describe('DELETE /api/admin/users/:id', () =>
296 299 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
297 300 expect([400]).toContain(status);
298 301 });
302
303 test('deletes an empty personal user folder when deleting that user account', async () =>
304 {
305 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
306 mockConfig.userPath = userFolderRoot;
307
308 const db = getDb();
309 const hash = bcrypt.hashSync('freshpass1', 4);
310 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
311 .run(['emptyfolderuser', hash, 0, '{}']);
312
313 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['emptyfolderuser']);
314 const folderPath = path.join(userFolderRoot, 'emptyfolderuser');
315 fs.mkdirSync(folderPath, { recursive: true });
316
317 try
318 {
319 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
320 expect(status).toBe(200);
321 expect(body.ok).toBe(true);
322 expect(fs.existsSync(folderPath)).toBe(false);
323 } finally
324 {
325 mockConfig.userPath = null;
326 fs.rmSync(userFolderRoot, { recursive: true, force: true });
327 }
328 });
329
330 test('keeps non-empty personal user folder when deleting that user account', async () =>
331 {
332 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
333 mockConfig.userPath = userFolderRoot;
334
335 const db = getDb();
336 const hash = bcrypt.hashSync('freshpass2', 4);
337 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
338 .run(['nonemptyuser', hash, 0, '{}']);
339
340 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['nonemptyuser']);
341 const folderPath = path.join(userFolderRoot, 'nonemptyuser');
342 fs.mkdirSync(folderPath, { recursive: true });
343 fs.writeFileSync(path.join(folderPath, 'keep.txt'), 'keep');
344
345 try
346 {
347 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
348 expect(status).toBe(200);
349 expect(body.ok).toBe(true);
350 expect(fs.existsSync(folderPath)).toBe(true);
351 } finally
352 {
353 mockConfig.userPath = null;
354 fs.rmSync(userFolderRoot, { recursive: true, force: true });
355 }
356 });
357 });
358
359 describe('GET /api/admin/orphan-userfolders', () =>
360 {
361 test('returns only non-empty orphaned folders and deletes empty orphan folders', async () =>
362 {
363 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
364 mockConfig.userPath = userFolderRoot;
365
366 const linkedFolder = path.join(userFolderRoot, 'linkeduser');
367 const orphanFolder = path.join(userFolderRoot, 'ghostuser');
368 const emptyOrphanFolder = path.join(userFolderRoot, 'emptyghost');
369
370 fs.mkdirSync(linkedFolder, { recursive: true });
371 fs.mkdirSync(orphanFolder, { recursive: true });
372 fs.mkdirSync(emptyOrphanFolder, { recursive: true });
373 fs.writeFileSync(path.join(orphanFolder, 'file.txt'), 'hello');
374
375 const db = getDb();
376 const hash = bcrypt.hashSync('linked-pass1', 4);
377 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
378 .run(['linkeduser', hash, 0, '{}']);
379
380 try
381 {
382 const { status, body } = await req('GET', '/api/admin/orphan-userfolders');
383 expect(status).toBe(200);
384 expect(Array.isArray(body.folders)).toBe(true);
385 expect(body.folders).toEqual([
386 {
387 folderName: 'ghostuser',
388 path: orphanFolder,
389 itemCount: 1,
390 },
391 ]);
392 expect(fs.existsSync(emptyOrphanFolder)).toBe(false);
393 } finally
394 {
395 mockConfig.userPath = null;
396 fs.rmSync(userFolderRoot, { recursive: true, force: true });
397 }
398 });
299 399 });
300 400
301 401 describe('GET /api/admin/config', () =>
@@ -8,6 +8,9 @@ const express = require('express');
8const http = require('http');
8const http = require('http');
9const { once } = require('events');
9const { once } = require('events');
10const crypto = require('crypto');
10const crypto = require('crypto');
11const fs = require('fs');
12const os = require('os');
13const path = require('path');
11
14
12// ── child_process mock — controlled per test ──────────────────────────────────
15// ── child_process mock — controlled per test ──────────────────────────────────
13let mockExecFileImpl = null;
16let mockExecFileImpl = null;
@@ -61,7 +64,7 @@ jest.mock('../server/db', () =>
61});
64});
62
65
63// ── config mock ─────────────────────────────────────────────────────────────
66// ── config mock ─────────────────────────────────────────────────────────────
64const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
67const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
65jest.mock('../server/config', () => ({
68jest.mock('../server/config', () => ({
66 loadConfig: () => ({ ...mockConfig }),
69 loadConfig: () => ({ ...mockConfig }),
67 saveConfig: (c) => Object.assign(mockConfig, c),
70 saveConfig: (c) => Object.assign(mockConfig, c),
@@ -296,6 +299,103 @@ describe('DELETE /api/admin/users/:id', () =>
296 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
299 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
297 expect([400]).toContain(status);
300 expect([400]).toContain(status);
298 });
301 });
302
303 test('deletes an empty personal user folder when deleting that user account', async () =>
304 {
305 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
306 mockConfig.userPath = userFolderRoot;
307
308 const db = getDb();
309 const hash = bcrypt.hashSync('freshpass1', 4);
310 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
311 .run(['emptyfolderuser', hash, 0, '{}']);
312
313 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['emptyfolderuser']);
314 const folderPath = path.join(userFolderRoot, 'emptyfolderuser');
315 fs.mkdirSync(folderPath, { recursive: true });
316
317 try
318 {
319 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
320 expect(status).toBe(200);
321 expect(body.ok).toBe(true);
322 expect(fs.existsSync(folderPath)).toBe(false);
323 } finally
324 {
325 mockConfig.userPath = null;
326 fs.rmSync(userFolderRoot, { recursive: true, force: true });
327 }
328 });
329
330 test('keeps non-empty personal user folder when deleting that user account', async () =>
331 {
332 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
333 mockConfig.userPath = userFolderRoot;
334
335 const db = getDb();
336 const hash = bcrypt.hashSync('freshpass2', 4);
337 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
338 .run(['nonemptyuser', hash, 0, '{}']);
339
340 const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['nonemptyuser']);
341 const folderPath = path.join(userFolderRoot, 'nonemptyuser');
342 fs.mkdirSync(folderPath, { recursive: true });
343 fs.writeFileSync(path.join(folderPath, 'keep.txt'), 'keep');
344
345 try
346 {
347 const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`);
348 expect(status).toBe(200);
349 expect(body.ok).toBe(true);
350 expect(fs.existsSync(folderPath)).toBe(true);
351 } finally
352 {
353 mockConfig.userPath = null;
354 fs.rmSync(userFolderRoot, { recursive: true, force: true });
355 }
356 });
357});
358
359describe('GET /api/admin/orphan-userfolders', () =>
360{
361 test('returns only non-empty orphaned folders and deletes empty orphan folders', async () =>
362 {
363 const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-'));
364 mockConfig.userPath = userFolderRoot;
365
366 const linkedFolder = path.join(userFolderRoot, 'linkeduser');
367 const orphanFolder = path.join(userFolderRoot, 'ghostuser');
368 const emptyOrphanFolder = path.join(userFolderRoot, 'emptyghost');
369
370 fs.mkdirSync(linkedFolder, { recursive: true });
371 fs.mkdirSync(orphanFolder, { recursive: true });
372 fs.mkdirSync(emptyOrphanFolder, { recursive: true });
373 fs.writeFileSync(path.join(orphanFolder, 'file.txt'), 'hello');
374
375 const db = getDb();
376 const hash = bcrypt.hashSync('linked-pass1', 4);
377 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
378 .run(['linkeduser', hash, 0, '{}']);
379
380 try
381 {
382 const { status, body } = await req('GET', '/api/admin/orphan-userfolders');
383 expect(status).toBe(200);
384 expect(Array.isArray(body.folders)).toBe(true);
385 expect(body.folders).toEqual([
386 {
387 folderName: 'ghostuser',
388 path: orphanFolder,
389 itemCount: 1,
390 },
391 ]);
392 expect(fs.existsSync(emptyOrphanFolder)).toBe(false);
393 } finally
394 {
395 mockConfig.userPath = null;
396 fs.rmSync(userFolderRoot, { recursive: true, force: true });
397 }
398 });
299});
399});
300
400
301describe('GET /api/admin/config', () =>
401describe('GET /api/admin/config', () =>
tests/files.routes.test.js +59 −0
@@ -612,6 +612,65 @@ describe('GET /api/files/root-access', () =>
612 612 });
613 613 });
614 614
615 describe('orphaned user folder access', () =>
616 {
617 test('admins can read and write in orphaned user folders', async () =>
618 {
619 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
620 const orphanFolder = path.join(userFolderBase, 'ghost-user');
621 fs.mkdirSync(orphanFolder, { recursive: true });
622 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
623
624 mockUserPath = userFolderBase;
625 mockUser = {
626 username: 'admin',
627 isAdmin: true,
628 permissions: {},
629 };
630
631 try
632 {
633 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
634 expect(listRes.status).toBe(200);
635 expect(Array.isArray(listRes.body.items)).toBe(true);
636 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
637
638 const mkdirRes = await req('POST', '/api/files/mkdir', {
639 dir: orphanFolder,
640 name: 'created-by-admin',
641 });
642 expect(mkdirRes.status).toBe(200);
643 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
644 } finally
645 {
646 fs.rmSync(userFolderBase, { recursive: true, force: true });
647 }
648 });
649
650 test('non-admin users cannot access orphaned user folders', async () =>
651 {
652 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
653 const orphanFolder = path.join(userFolderBase, 'ghost-user');
654 fs.mkdirSync(orphanFolder, { recursive: true });
655
656 mockUserPath = userFolderBase;
657 mockUser = {
658 username: 'alice',
659 isAdmin: false,
660 permissions: {},
661 };
662
663 try
664 {
665 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
666 expect(listRes.status).toBe(403);
667 } finally
668 {
669 fs.rmSync(userFolderBase, { recursive: true, force: true });
670 }
671 });
672 });
673
615 674 describe('folder icon endpoints', () =>
616 675 {
617 676 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
@@ -612,6 +612,65 @@ describe('GET /api/files/root-access', () =>
612 });
612 });
613});
613});
614
614
615describe('orphaned user folder access', () =>
616{
617 test('admins can read and write in orphaned user folders', async () =>
618 {
619 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
620 const orphanFolder = path.join(userFolderBase, 'ghost-user');
621 fs.mkdirSync(orphanFolder, { recursive: true });
622 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
623
624 mockUserPath = userFolderBase;
625 mockUser = {
626 username: 'admin',
627 isAdmin: true,
628 permissions: {},
629 };
630
631 try
632 {
633 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
634 expect(listRes.status).toBe(200);
635 expect(Array.isArray(listRes.body.items)).toBe(true);
636 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
637
638 const mkdirRes = await req('POST', '/api/files/mkdir', {
639 dir: orphanFolder,
640 name: 'created-by-admin',
641 });
642 expect(mkdirRes.status).toBe(200);
643 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
644 } finally
645 {
646 fs.rmSync(userFolderBase, { recursive: true, force: true });
647 }
648 });
649
650 test('non-admin users cannot access orphaned user folders', async () =>
651 {
652 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
653 const orphanFolder = path.join(userFolderBase, 'ghost-user');
654 fs.mkdirSync(orphanFolder, { recursive: true });
655
656 mockUserPath = userFolderBase;
657 mockUser = {
658 username: 'alice',
659 isAdmin: false,
660 permissions: {},
661 };
662
663 try
664 {
665 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
666 expect(listRes.status).toBe(403);
667 } finally
668 {
669 fs.rmSync(userFolderBase, { recursive: true, force: true });
670 }
671 });
672});
673
615describe('folder icon endpoints', () =>
674describe('folder icon endpoints', () =>
616{
675{
617 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
676 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
tests/page.load.test.js +62 −0
@@ -25,6 +25,7 @@ describe('page load smoke test', () =>
25 25 let rootAccessFixture;
26 26 let folderIconFixture;
27 27 let adminUsersFixture;
28 let orphanUserFoldersFixture;
28 29 let adminConfigFixture;
29 30 let updateStatusFixture;
30 31 let downloadFixture;
@@ -57,6 +58,7 @@ describe('page load smoke test', () =>
57 58 rootAccessFixture = {};
58 59 folderIconFixture = {};
59 60 adminUsersFixture = { users: [] };
61 orphanUserFoldersFixture = { folders: [] };
60 62 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
61 63 updateStatusFixture = { underSystemd: false, commitsAhead: [] };
62 64 downloadFixture = {};
@@ -195,6 +197,7 @@ describe('page load smoke test', () =>
195 197 });
196 198 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
197 199 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
200 app.get('/api/admin/orphan-userfolders', (req, res) => res.json(orphanUserFoldersFixture));
198 201 app.get('/api/admin/update-status', (req, res) => res.json(updateStatusFixture));
199 202 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
200 203 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
@@ -918,6 +921,65 @@ describe('page load smoke test', () =>
918 921 dom.window.close();
919 922 });
920 923
924 test('admin panel hides orphaned user folders subsection when there are no orphan folders', async () =>
925 {
926 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
927 orphanUserFoldersFixture = { folders: [] };
928
929 const { dom, runtimeErrors } = await bootClient();
930 expect(runtimeErrors).toEqual([]);
931
932 dom.window.document.getElementById('btn-admin').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
933 await new Promise(resolve => dom.window.setTimeout(resolve, 80));
934
935 const section = dom.window.document.getElementById('admin-orphan-userfolders-section');
936 expect(section).toBeTruthy();
937 expect(section.classList.contains('hidden')).toBe(true);
938
939 dom.window.close();
940 });
941
942 test('admin panel lists orphaned user folders and open button navigates into that folder', async () =>
943 {
944 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
945 orphanUserFoldersFixture = {
946 folders: [
947 {
948 folderName: 'ghost-user',
949 path: '/userfolders/ghost-user',
950 itemCount: 1,
951 },
952 ],
953 };
954 listFixture['/userfolders/ghost-user'] = [
955 {
956 name: 'leftover.txt',
957 path: '/userfolders/ghost-user/leftover.txt',
958 isDir: false,
959 size: 20,
960 mtime: Date.now(),
961 },
962 ];
963
964 const { dom, runtimeErrors } = await bootClient();
965 expect(runtimeErrors).toEqual([]);
966
967 dom.window.document.getElementById('btn-admin').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
968 await new Promise(resolve => dom.window.setTimeout(resolve, 80));
969
970 const section = dom.window.document.getElementById('admin-orphan-userfolders-section');
971 expect(section.classList.contains('hidden')).toBe(false);
972
973 const openBtn = dom.window.document.querySelector('#admin-orphan-userfolders-list [data-action="open-orphan-folder"]');
974 expect(openBtn).toBeTruthy();
975 openBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
976
977 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/userfolders/ghost-user/leftover.txt"]'));
978 expect(dom.window.document.getElementById('admin-modal').classList.contains('hidden')).toBe(true);
979
980 dom.window.close();
981 });
982
921 983 test('admin topbar shows update badge after login when updates are available', async () =>
922 984 {
923 985 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
@@ -25,6 +25,7 @@ describe('page load smoke test', () =>
25 let rootAccessFixture;
25 let rootAccessFixture;
26 let folderIconFixture;
26 let folderIconFixture;
27 let adminUsersFixture;
27 let adminUsersFixture;
28 let orphanUserFoldersFixture;
28 let adminConfigFixture;
29 let adminConfigFixture;
29 let updateStatusFixture;
30 let updateStatusFixture;
30 let downloadFixture;
31 let downloadFixture;
@@ -57,6 +58,7 @@ describe('page load smoke test', () =>
57 rootAccessFixture = {};
58 rootAccessFixture = {};
58 folderIconFixture = {};
59 folderIconFixture = {};
59 adminUsersFixture = { users: [] };
60 adminUsersFixture = { users: [] };
61 orphanUserFoldersFixture = { folders: [] };
60 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
62 adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
61 updateStatusFixture = { underSystemd: false, commitsAhead: [] };
63 updateStatusFixture = { underSystemd: false, commitsAhead: [] };
62 downloadFixture = {};
64 downloadFixture = {};
@@ -195,6 +197,7 @@ describe('page load smoke test', () =>
195 });
197 });
196 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
198 app.get('/api/admin/config', (req, res) => res.json(adminConfigFixture));
197 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
199 app.get('/api/admin/users', (req, res) => res.json(adminUsersFixture));
200 app.get('/api/admin/orphan-userfolders', (req, res) => res.json(orphanUserFoldersFixture));
198 app.get('/api/admin/update-status', (req, res) => res.json(updateStatusFixture));
201 app.get('/api/admin/update-status', (req, res) => res.json(updateStatusFixture));
199 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
202 app.post('/api/auth/logout', (req, res) => res.json({ ok: true }));
200 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
203 app.get('*', (req, res) => res.sendFile(path.join(publicDir, 'index.html')));
@@ -918,6 +921,65 @@ describe('page load smoke test', () =>
918 dom.window.close();
921 dom.window.close();
919 });
922 });
920
923
924 test('admin panel hides orphaned user folders subsection when there are no orphan folders', async () =>
925 {
926 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
927 orphanUserFoldersFixture = { folders: [] };
928
929 const { dom, runtimeErrors } = await bootClient();
930 expect(runtimeErrors).toEqual([]);
931
932 dom.window.document.getElementById('btn-admin').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
933 await new Promise(resolve => dom.window.setTimeout(resolve, 80));
934
935 const section = dom.window.document.getElementById('admin-orphan-userfolders-section');
936 expect(section).toBeTruthy();
937 expect(section.classList.contains('hidden')).toBe(true);
938
939 dom.window.close();
940 });
941
942 test('admin panel lists orphaned user folders and open button navigates into that folder', async () =>
943 {
944 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
945 orphanUserFoldersFixture = {
946 folders: [
947 {
948 folderName: 'ghost-user',
949 path: '/userfolders/ghost-user',
950 itemCount: 1,
951 },
952 ],
953 };
954 listFixture['/userfolders/ghost-user'] = [
955 {
956 name: 'leftover.txt',
957 path: '/userfolders/ghost-user/leftover.txt',
958 isDir: false,
959 size: 20,
960 mtime: Date.now(),
961 },
962 ];
963
964 const { dom, runtimeErrors } = await bootClient();
965 expect(runtimeErrors).toEqual([]);
966
967 dom.window.document.getElementById('btn-admin').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
968 await new Promise(resolve => dom.window.setTimeout(resolve, 80));
969
970 const section = dom.window.document.getElementById('admin-orphan-userfolders-section');
971 expect(section.classList.contains('hidden')).toBe(false);
972
973 const openBtn = dom.window.document.querySelector('#admin-orphan-userfolders-list [data-action="open-orphan-folder"]');
974 expect(openBtn).toBeTruthy();
975 openBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
976
977 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/userfolders/ghost-user/leftover.txt"]'));
978 expect(dom.window.document.getElementById('admin-modal').classList.contains('hidden')).toBe(true);
979
980 dom.window.close();
981 });
982
921 test('admin topbar shows update badge after login when updates are available', async () =>
983 test('admin topbar shows update badge after login when updates are available', async () =>
922 {
984 {
923 meFixture = { username: 'admin', isAdmin: true, permissions: {} };
985 meFixture = { username: 'admin', isAdmin: true, permissions: {} };