BlueGit

timfa filemanager

Add root aliases and restrict root sidebar actions

timfa Tim Falken · pushed by timfa

Authored 2026-05-04 · 6 months ago

Hash
f86c6b26e9b892d3a5c2ce75c01b4de4f3ecf027
Parent
d953246b
7 files changed +270 −25
.github/technical-reference.md +7 −1
@@ -29,6 +29,10 @@
29 29 ## server/routes/admin.js
30 30 - POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
31 31
32 ## server/routes/files.js
33 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
34 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
35
32 36 ## public/app.js
33 37 - showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
34 38 - getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
@@ -65,13 +69,15 @@
65 69 - closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
66 70 - closePreview() - Closes expanded-tile preview and revokes active preview object URL.
67 71 - openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
72 - rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
68 73 - ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
69 74 - createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
70 75 - loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
71 76 - isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
72 77 - makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
73 78 - attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
74 - openSidebar(item) - Renders item details/actions in sidebar; root folders include used/remaining storage stats when focused from Home.
79 - openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
80 - openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
75 81
76 82 ## public/drag-move.js
77 83 - 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.
@@ -29,6 +29,10 @@
29## server/routes/admin.js
29## server/routes/admin.js
30- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
30- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
31
31
32## server/routes/files.js
33- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
34- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
35
32## public/app.js
36## public/app.js
33- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
37- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
34- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
38- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
@@ -65,13 +69,15 @@
65- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
69- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
66- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
70- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
67- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
71- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
72- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
68- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
73- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
69- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
74- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
70- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
75- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
71- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
76- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
72- makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
77- makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
73- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
78- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
74- openSidebar(item) - Renders item details/actions in sidebar; root folders include used/remaining storage stats when focused from Home.
79- openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
80- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
75
81
76## public/drag-move.js
82## public/drag-move.js
77- 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.
83- 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 +5 −0
@@ -38,6 +38,10 @@
38 38
39 39 ## `test/files.routes.test.js`
40 40 - `POST /api/files/move`
41 - `root alias endpoints`
42 - `GET /api/files/roots returns alias label and original name`
43 - `POST /api/files/root-alias stores alias without renaming filesystem path`
44 - `POST /api/files/root-alias rejects non-root paths`
41 45
42 46 ---
43 47
@@ -47,5 +51,6 @@
47 51 - `keeps sidebar folded on initial mobile boot`
48 52 - `suppresses default context menu on mobile file long-press`
49 53 - `in Home, root tiles single-click focus and double-click open`
54 - `root sidebar shows alias and original name, and excludes Move to action`
50 55
51 56 ---
@@ -38,6 +38,10 @@
38
38
39## `test/files.routes.test.js`
39## `test/files.routes.test.js`
40- `POST /api/files/move`
40- `POST /api/files/move`
41- `root alias endpoints`
42- `GET /api/files/roots returns alias label and original name`
43- `POST /api/files/root-alias stores alias without renaming filesystem path`
44- `POST /api/files/root-alias rejects non-root paths`
41
45
42---
46---
43
47
@@ -47,5 +51,6 @@
47- `keeps sidebar folded on initial mobile boot`
51- `keeps sidebar folded on initial mobile boot`
48- `suppresses default context menu on mobile file long-press`
52- `suppresses default context menu on mobile file long-press`
49- `in Home, root tiles single-click focus and double-click open`
53- `in Home, root tiles single-click focus and double-click open`
54- `root sidebar shows alias and original name, and excludes Move to action`
50
55
51---
56---
public/app.js +57 −17
@@ -1081,6 +1081,11 @@ async function openSidebar (item)
1081 1081
1082 1082 if (item._root)
1083 1083 {
1084 dl.innerHTML += `
1085 <dt>Alias</dt><dd>${item.name}</dd>
1086 <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd>
1087 `;
1088
1084 1089 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1085 1090 if (space)
1086 1091 {
@@ -1100,23 +1105,29 @@ async function openSidebar (item)
1100 1105 }
1101 1106
1102 1107 // Rename button (write access required)
1103 if (canWrite())
1108 if (canWrite(item))
1104 1109 {
1105 const btnMove = document.createElement('button');
1106 btnMove.textContent = 'Move to';
1107 btnMove.addEventListener('click', () => openMovePicker(item));
1108 actions.appendChild(btnMove);
1110 if (!item._root)
1111 {
1112 const btnMove = document.createElement('button');
1113 btnMove.textContent = 'Move to';
1114 btnMove.addEventListener('click', () => openMovePicker(item));
1115 actions.appendChild(btnMove);
1116 }
1109 1117
1110 1118 const btnRen = document.createElement('button');
1111 1119 btnRen.textContent = 'Rename';
1112 1120 btnRen.addEventListener('click', () => openRenameModal(item));
1113 1121 actions.appendChild(btnRen);
1114 1122
1115 const btnDel = document.createElement('button');
1116 btnDel.textContent = 'Delete';
1117 btnDel.className = 'danger';
1118 btnDel.addEventListener('click', () => deleteItem(item));
1119 actions.appendChild(btnDel);
1123 if (!item._root)
1124 {
1125 const btnDel = document.createElement('button');
1126 btnDel.textContent = 'Delete';
1127 btnDel.className = 'danger';
1128 btnDel.addEventListener('click', () => deleteItem(item));
1129 actions.appendChild(btnDel);
1130 }
1120 1131 }
1121 1132 }
1122 1133
@@ -1189,12 +1200,23 @@ function basenameOfPath (p)
1189 1200 return parts.length ? parts[parts.length - 1] : String(p || '');
1190 1201 }
1191 1202
1203 function rootPermissionLabel (root)
1204 {
1205 return (root && (root.originalName || root.label)) || '';
1206 }
1207
1208 function resolveRootForPath (targetPath)
1209 {
1210 if (!targetPath) return null;
1211 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
1212 }
1213
1192 1214 function writableRoots ()
1193 1215 {
1194 1216 if (STATE.isAdmin) return STATE.roots.slice();
1195 1217 return STATE.roots.filter((r) =>
1196 1218 {
1197 const perm = STATE.permissions[r.label];
1219 const perm = STATE.permissions[rootPermissionLabel(r)];
1198 1220 return !!(perm && perm.write);
1199 1221 });
1200 1222 }
@@ -1913,11 +1935,14 @@ async function downloadOrView (item, sourceSvgEl = null)
1913 1935 // UPLOAD
1914 1936 // ───────────────────────────────────────────────────────────────────────────
1915 1937
1916 function canWrite ()
1938 function canWrite (item = null)
1917 1939 {
1918 1940 if (STATE.isAdmin) return true;
1919 if (!STATE.currentRoot) return false;
1920 const p = STATE.permissions[STATE.currentRoot.label];
1941 const root = item && item._root
1942 ? item._root
1943 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
1944 if (!root) return false;
1945 const p = STATE.permissions[rootPermissionLabel(root)];
1921 1946 return p && p.write;
1922 1947 }
1923 1948
@@ -2254,10 +2279,25 @@ function openRenameModal (item)
2254 2279 if (!newName) return;
2255 2280 try
2256 2281 {
2257 await api('POST', '/files/rename', { from: item.path, to: newName });
2282 if (item._root)
2283 {
2284 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
2285 } else
2286 {
2287 await api('POST', '/files/rename', { from: item.path, to: newName });
2288 }
2258 2289 modal.classList.add('hidden');
2259 toast('Renamed.', 'ok');
2260 await navigateTo(STATE.currentDir, STATE.currentRoot);
2290 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
2291 if (item._root)
2292 {
2293 await loadRoots({
2294 preferredDir: STATE.currentDir,
2295 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
2296 });
2297 } else
2298 {
2299 await navigateTo(STATE.currentDir, STATE.currentRoot);
2300 }
2261 2301 } catch (err)
2262 2302 {
2263 2303 document.getElementById('rename-error').textContent = err.message;
@@ -1081,6 +1081,11 @@ async function openSidebar (item)
1081
1081
1082 if (item._root)
1082 if (item._root)
1083 {
1083 {
1084 dl.innerHTML += `
1085 <dt>Alias</dt><dd>${item.name}</dd>
1086 <dt>Original name</dt><dd>${item._root.originalName || basenameOfPath(item.path)}</dd>
1087 `;
1088
1084 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1089 const space = await api('GET', `/files/space?dir=${encodeURIComponent(item.path)}`).catch(() => null);
1085 if (space)
1090 if (space)
1086 {
1091 {
@@ -1100,23 +1105,29 @@ async function openSidebar (item)
1100 }
1105 }
1101
1106
1102 // Rename button (write access required)
1107 // Rename button (write access required)
1103 if (canWrite())
1108 if (canWrite(item))
1104 {
1109 {
1105 const btnMove = document.createElement('button');
1110 if (!item._root)
1106 btnMove.textContent = 'Move to';
1111 {
1107 btnMove.addEventListener('click', () => openMovePicker(item));
1112 const btnMove = document.createElement('button');
1108 actions.appendChild(btnMove);
1113 btnMove.textContent = 'Move to';
1114 btnMove.addEventListener('click', () => openMovePicker(item));
1115 actions.appendChild(btnMove);
1116 }
1109
1117
1110 const btnRen = document.createElement('button');
1118 const btnRen = document.createElement('button');
1111 btnRen.textContent = 'Rename';
1119 btnRen.textContent = 'Rename';
1112 btnRen.addEventListener('click', () => openRenameModal(item));
1120 btnRen.addEventListener('click', () => openRenameModal(item));
1113 actions.appendChild(btnRen);
1121 actions.appendChild(btnRen);
1114
1122
1115 const btnDel = document.createElement('button');
1123 if (!item._root)
1116 btnDel.textContent = 'Delete';
1124 {
1117 btnDel.className = 'danger';
1125 const btnDel = document.createElement('button');
1118 btnDel.addEventListener('click', () => deleteItem(item));
1126 btnDel.textContent = 'Delete';
1119 actions.appendChild(btnDel);
1127 btnDel.className = 'danger';
1128 btnDel.addEventListener('click', () => deleteItem(item));
1129 actions.appendChild(btnDel);
1130 }
1120 }
1131 }
1121}
1132}
1122
1133
@@ -1189,12 +1200,23 @@ function basenameOfPath (p)
1189 return parts.length ? parts[parts.length - 1] : String(p || '');
1200 return parts.length ? parts[parts.length - 1] : String(p || '');
1190}
1201}
1191
1202
1203function rootPermissionLabel (root)
1204{
1205 return (root && (root.originalName || root.label)) || '';
1206}
1207
1208function resolveRootForPath (targetPath)
1209{
1210 if (!targetPath) return null;
1211 return STATE.roots.find((r) => samePath(targetPath, r.path) || pathInside(targetPath, r.path)) || null;
1212}
1213
1192function writableRoots ()
1214function writableRoots ()
1193{
1215{
1194 if (STATE.isAdmin) return STATE.roots.slice();
1216 if (STATE.isAdmin) return STATE.roots.slice();
1195 return STATE.roots.filter((r) =>
1217 return STATE.roots.filter((r) =>
1196 {
1218 {
1197 const perm = STATE.permissions[r.label];
1219 const perm = STATE.permissions[rootPermissionLabel(r)];
1198 return !!(perm && perm.write);
1220 return !!(perm && perm.write);
1199 });
1221 });
1200}
1222}
@@ -1913,11 +1935,14 @@ async function downloadOrView (item, sourceSvgEl = null)
1913// UPLOAD
1935// UPLOAD
1914// ───────────────────────────────────────────────────────────────────────────
1936// ───────────────────────────────────────────────────────────────────────────
1915
1937
1916function canWrite ()
1938function canWrite (item = null)
1917{
1939{
1918 if (STATE.isAdmin) return true;
1940 if (STATE.isAdmin) return true;
1919 if (!STATE.currentRoot) return false;
1941 const root = item && item._root
1920 const p = STATE.permissions[STATE.currentRoot.label];
1942 ? item._root
1943 : (STATE.currentRoot || (item ? resolveRootForPath(item.path) : null));
1944 if (!root) return false;
1945 const p = STATE.permissions[rootPermissionLabel(root)];
1921 return p && p.write;
1946 return p && p.write;
1922}
1947}
1923
1948
@@ -2254,10 +2279,25 @@ function openRenameModal (item)
2254 if (!newName) return;
2279 if (!newName) return;
2255 try
2280 try
2256 {
2281 {
2257 await api('POST', '/files/rename', { from: item.path, to: newName });
2282 if (item._root)
2283 {
2284 await api('POST', '/files/root-alias', { rootPath: item.path, alias: newName });
2285 } else
2286 {
2287 await api('POST', '/files/rename', { from: item.path, to: newName });
2288 }
2258 modal.classList.add('hidden');
2289 modal.classList.add('hidden');
2259 toast('Renamed.', 'ok');
2290 toast(item._root ? 'Alias updated.' : 'Renamed.', 'ok');
2260 await navigateTo(STATE.currentDir, STATE.currentRoot);
2291 if (item._root)
2292 {
2293 await loadRoots({
2294 preferredDir: STATE.currentDir,
2295 preferredRootPath: (STATE.currentRoot && STATE.currentRoot.path) || item.path,
2296 });
2297 } else
2298 {
2299 await navigateTo(STATE.currentDir, STATE.currentRoot);
2300 }
2261 } catch (err)
2301 } catch (err)
2262 {
2302 {
2263 document.getElementById('rename-error').textContent = err.message;
2303 document.getElementById('rename-error').textContent = err.message;
server/config.js +11 −2
@@ -10,10 +10,19 @@ function loadConfig ()
10 10 try
11 11 {
12 12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
13 return JSON.parse(raw);
13 const parsed = JSON.parse(raw);
14 if (!parsed || typeof parsed !== 'object')
15 {
16 return { port: 3000, paths: [], rootAliases: {} };
17 }
18 if (!parsed.rootAliases || typeof parsed.rootAliases !== 'object')
19 {
20 parsed.rootAliases = {};
21 }
22 return parsed;
14 23 } catch
15 24 {
16 const defaults = { port: 3000, paths: [] };
25 const defaults = { port: 3000, paths: [], rootAliases: {} };
17 26 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
18 27 return defaults;
19 28 }
@@ -10,10 +10,19 @@ function loadConfig ()
10 try
10 try
11 {
11 {
12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
13 return JSON.parse(raw);
13 const parsed = JSON.parse(raw);
14 if (!parsed || typeof parsed !== 'object')
15 {
16 return { port: 3000, paths: [], rootAliases: {} };
17 }
18 if (!parsed.rootAliases || typeof parsed.rootAliases !== 'object')
19 {
20 parsed.rootAliases = {};
21 }
22 return parsed;
14 } catch
23 } catch
15 {
24 {
16 const defaults = { port: 3000, paths: [] };
25 const defaults = { port: 3000, paths: [], rootAliases: {} };
17 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
26 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
18 return defaults;
27 return defaults;
19 }
28 }
server/routes/files.js +73 −3
@@ -7,7 +7,7 @@ const multer = require('multer');
7 7 const router = express.Router();
8 8
9 9 const { getDb } = require('../db');
10 const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
10 const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11 11 const { requireAuth } = require('../auth');
12 12
13 13 // ---------------------------------------------------------------------------
@@ -40,6 +40,13 @@ function effectivePaths ()
40 40 return getEffectivePaths(loadConfig().paths || []);
41 41 }
42 42
43 function rootAliasesFromConfig (config)
44 {
45 if (!config || typeof config !== 'object') return {};
46 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
47 return config.rootAliases;
48 }
49
43 50 function getFreeBytes (targetPath)
44 51 {
45 52 if (typeof fs.statfsSync !== 'function') return null;
@@ -166,13 +173,76 @@ function rewriteMetaPaths (fromPath, toPath)
166 173 // ---------------------------------------------------------------------------
167 174 router.get('/roots', requireAuth, (req, res) =>
168 175 {
169 const roots = effectivePaths();
176 const config = loadConfig();
177 const roots = getEffectivePaths(config.paths || []);
178 const rootAliases = rootAliasesFromConfig(config);
179
170 180 const readable = roots
171 181 .filter(r => canRead(req.user, path.basename(r)))
172 .map(r => ({ label: path.basename(r), path: r }));
182 .map(r =>
183 {
184 const originalName = path.basename(r);
185 const alias = String(rootAliases[path.resolve(r)] || '').trim();
186 return {
187 label: alias || originalName,
188 path: r,
189 originalName,
190 alias: alias || null,
191 };
192 });
173 193 res.json({ roots: readable });
174 194 });
175 195
196 // ---------------------------------------------------------------------------
197 // POST /api/files/root-alias
198 // Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
199 // Sets a display-only alias for a configured root.
200 // ---------------------------------------------------------------------------
201 router.post('/root-alias', requireAuth, (req, res) =>
202 {
203 const rootPath = String(req.body && req.body.rootPath || '').trim();
204 const alias = String(req.body && req.body.alias || '').trim();
205 if (!rootPath || !alias)
206 {
207 return res.status(400).json({ error: 'rootPath and alias are required.' });
208 }
209
210 const roots = effectivePaths();
211 const info = resolveRoot(rootPath, roots);
212 if (!info) return res.status(403).json({ error: 'Access denied.' });
213 if (!sameResolvedPath(rootPath, info.root))
214 {
215 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
216 }
217 if (!canWrite(req.user, info.label))
218 {
219 return res.status(403).json({ error: 'Access denied.' });
220 }
221
222 const config = loadConfig();
223 const rootAliases = rootAliasesFromConfig(config);
224 const key = path.resolve(info.root);
225 if (alias === info.label)
226 {
227 delete rootAliases[key];
228 } else
229 {
230 rootAliases[key] = alias;
231 }
232 config.rootAliases = rootAliases;
233 saveConfig(config);
234
235 res.json({
236 ok: true,
237 root: {
238 path: info.root,
239 label: alias,
240 originalName: info.label,
241 alias,
242 },
243 });
244 });
245
176 246 // ---------------------------------------------------------------------------
177 247 // GET /api/files/list?dir=<absolute-path>
178 248 // Lists files and folders in the given directory.
@@ -7,7 +7,7 @@ const multer = require('multer');
7const router = express.Router();
7const router = express.Router();
8
8
9const { getDb } = require('../db');
9const { getDb } = require('../db');
10const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
10const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
11const { requireAuth } = require('../auth');
12
12
13// ---------------------------------------------------------------------------
13// ---------------------------------------------------------------------------
@@ -40,6 +40,13 @@ function effectivePaths ()
40 return getEffectivePaths(loadConfig().paths || []);
40 return getEffectivePaths(loadConfig().paths || []);
41}
41}
42
42
43function rootAliasesFromConfig (config)
44{
45 if (!config || typeof config !== 'object') return {};
46 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
47 return config.rootAliases;
48}
49
43function getFreeBytes (targetPath)
50function getFreeBytes (targetPath)
44{
51{
45 if (typeof fs.statfsSync !== 'function') return null;
52 if (typeof fs.statfsSync !== 'function') return null;
@@ -166,13 +173,76 @@ function rewriteMetaPaths (fromPath, toPath)
166// ---------------------------------------------------------------------------
173// ---------------------------------------------------------------------------
167router.get('/roots', requireAuth, (req, res) =>
174router.get('/roots', requireAuth, (req, res) =>
168{
175{
169 const roots = effectivePaths();
176 const config = loadConfig();
177 const roots = getEffectivePaths(config.paths || []);
178 const rootAliases = rootAliasesFromConfig(config);
179
170 const readable = roots
180 const readable = roots
171 .filter(r => canRead(req.user, path.basename(r)))
181 .filter(r => canRead(req.user, path.basename(r)))
172 .map(r => ({ label: path.basename(r), path: r }));
182 .map(r =>
183 {
184 const originalName = path.basename(r);
185 const alias = String(rootAliases[path.resolve(r)] || '').trim();
186 return {
187 label: alias || originalName,
188 path: r,
189 originalName,
190 alias: alias || null,
191 };
192 });
173 res.json({ roots: readable });
193 res.json({ roots: readable });
174});
194});
175
195
196// ---------------------------------------------------------------------------
197// POST /api/files/root-alias
198// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
199// Sets a display-only alias for a configured root.
200// ---------------------------------------------------------------------------
201router.post('/root-alias', requireAuth, (req, res) =>
202{
203 const rootPath = String(req.body && req.body.rootPath || '').trim();
204 const alias = String(req.body && req.body.alias || '').trim();
205 if (!rootPath || !alias)
206 {
207 return res.status(400).json({ error: 'rootPath and alias are required.' });
208 }
209
210 const roots = effectivePaths();
211 const info = resolveRoot(rootPath, roots);
212 if (!info) return res.status(403).json({ error: 'Access denied.' });
213 if (!sameResolvedPath(rootPath, info.root))
214 {
215 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
216 }
217 if (!canWrite(req.user, info.label))
218 {
219 return res.status(403).json({ error: 'Access denied.' });
220 }
221
222 const config = loadConfig();
223 const rootAliases = rootAliasesFromConfig(config);
224 const key = path.resolve(info.root);
225 if (alias === info.label)
226 {
227 delete rootAliases[key];
228 } else
229 {
230 rootAliases[key] = alias;
231 }
232 config.rootAliases = rootAliases;
233 saveConfig(config);
234
235 res.json({
236 ok: true,
237 root: {
238 path: info.root,
239 label: alias,
240 originalName: info.label,
241 alias,
242 },
243 });
244});
245
176// ---------------------------------------------------------------------------
246// ---------------------------------------------------------------------------
177// GET /api/files/list?dir=<absolute-path>
247// GET /api/files/list?dir=<absolute-path>
178// Lists files and folders in the given directory.
248// Lists files and folders in the given directory.
tests/files.routes.test.js +65 −1
@@ -8,6 +8,7 @@ const path = require('path');
8 8 const { once } = require('events');
9 9
10 10 let mockPaths = [];
11 let mockRootAliases = {};
11 12 let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
12 13
13 14 jest.mock('../server/db', () =>
@@ -33,7 +34,12 @@ jest.mock('../server/db', () =>
33 34 });
34 35
35 36 jest.mock('../server/config', () => ({
36 loadConfig: () => ({ port: 3000, paths: [...mockPaths] }),
37 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
38 saveConfig: (config) =>
39 {
40 mockPaths = [...(config.paths || [])];
41 mockRootAliases = { ...(config.rootAliases || {}) };
42 },
37 43 getEffectivePaths: (paths) => paths,
38 44 getAllowedRoot: (targetPath, roots) =>
39 45 {
@@ -87,6 +93,8 @@ beforeEach(() =>
87 93 {
88 94 fs.rmSync(rootDir, { recursive: true, force: true });
89 95 fs.mkdirSync(rootDir, { recursive: true });
96 mockRootAliases = {};
97 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
90 98 const db = getDb();
91 99 db.prepare('DELETE FROM file_meta').run([]);
92 100 });
@@ -172,3 +180,59 @@ describe('POST /api/files/move', () =>
172 180 expect(body.error).toMatch(/folder into itself/i);
173 181 });
174 182 });
183
184 describe('root alias endpoints', () =>
185 {
186 test('GET /api/files/roots returns alias label and original name', async () =>
187 {
188 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
189
190 const { status, body } = await req('GET', '/api/files/roots');
191
192 expect(status).toBe(200);
193 expect(body.roots).toHaveLength(1);
194 expect(body.roots[0]).toMatchObject({
195 path: rootDir,
196 label: 'Workspace',
197 alias: 'Workspace',
198 originalName: path.basename(rootDir),
199 });
200 });
201
202 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
203 {
204 const originalBase = path.basename(rootDir);
205 const { status, body } = await req('POST', '/api/files/root-alias', {
206 rootPath: rootDir,
207 alias: 'Shared Files',
208 });
209
210 expect(status).toBe(200);
211 expect(body.ok).toBe(true);
212 expect(body.root).toMatchObject({
213 path: rootDir,
214 label: 'Shared Files',
215 alias: 'Shared Files',
216 originalName: originalBase,
217 });
218 expect(fs.existsSync(rootDir)).toBe(true);
219
220 const afterRoots = await req('GET', '/api/files/roots');
221 expect(afterRoots.status).toBe(200);
222 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
223 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
224 });
225
226 test('POST /api/files/root-alias rejects non-root paths', async () =>
227 {
228 const nested = path.join(rootDir, 'sub');
229 fs.mkdirSync(nested, { recursive: true });
230
231 const { status } = await req('POST', '/api/files/root-alias', {
232 rootPath: nested,
233 alias: 'Nested',
234 });
235
236 expect(status).toBe(400);
237 });
238 });
@@ -8,6 +8,7 @@ const path = require('path');
8const { once } = require('events');
8const { once } = require('events');
9
9
10let mockPaths = [];
10let mockPaths = [];
11let mockRootAliases = {};
11let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
12let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
12
13
13jest.mock('../server/db', () =>
14jest.mock('../server/db', () =>
@@ -33,7 +34,12 @@ jest.mock('../server/db', () =>
33});
34});
34
35
35jest.mock('../server/config', () => ({
36jest.mock('../server/config', () => ({
36 loadConfig: () => ({ port: 3000, paths: [...mockPaths] }),
37 loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }),
38 saveConfig: (config) =>
39 {
40 mockPaths = [...(config.paths || [])];
41 mockRootAliases = { ...(config.rootAliases || {}) };
42 },
37 getEffectivePaths: (paths) => paths,
43 getEffectivePaths: (paths) => paths,
38 getAllowedRoot: (targetPath, roots) =>
44 getAllowedRoot: (targetPath, roots) =>
39 {
45 {
@@ -87,6 +93,8 @@ beforeEach(() =>
87{
93{
88 fs.rmSync(rootDir, { recursive: true, force: true });
94 fs.rmSync(rootDir, { recursive: true, force: true });
89 fs.mkdirSync(rootDir, { recursive: true });
95 fs.mkdirSync(rootDir, { recursive: true });
96 mockRootAliases = {};
97 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
90 const db = getDb();
98 const db = getDb();
91 db.prepare('DELETE FROM file_meta').run([]);
99 db.prepare('DELETE FROM file_meta').run([]);
92});
100});
@@ -172,3 +180,59 @@ describe('POST /api/files/move', () =>
172 expect(body.error).toMatch(/folder into itself/i);
180 expect(body.error).toMatch(/folder into itself/i);
173 });
181 });
174});
182});
183
184describe('root alias endpoints', () =>
185{
186 test('GET /api/files/roots returns alias label and original name', async () =>
187 {
188 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
189
190 const { status, body } = await req('GET', '/api/files/roots');
191
192 expect(status).toBe(200);
193 expect(body.roots).toHaveLength(1);
194 expect(body.roots[0]).toMatchObject({
195 path: rootDir,
196 label: 'Workspace',
197 alias: 'Workspace',
198 originalName: path.basename(rootDir),
199 });
200 });
201
202 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
203 {
204 const originalBase = path.basename(rootDir);
205 const { status, body } = await req('POST', '/api/files/root-alias', {
206 rootPath: rootDir,
207 alias: 'Shared Files',
208 });
209
210 expect(status).toBe(200);
211 expect(body.ok).toBe(true);
212 expect(body.root).toMatchObject({
213 path: rootDir,
214 label: 'Shared Files',
215 alias: 'Shared Files',
216 originalName: originalBase,
217 });
218 expect(fs.existsSync(rootDir)).toBe(true);
219
220 const afterRoots = await req('GET', '/api/files/roots');
221 expect(afterRoots.status).toBe(200);
222 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
223 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
224 });
225
226 test('POST /api/files/root-alias rejects non-root paths', async () =>
227 {
228 const nested = path.join(rootDir, 'sub');
229 fs.mkdirSync(nested, { recursive: true });
230
231 const { status } = await req('POST', '/api/files/root-alias', {
232 rootPath: nested,
233 alias: 'Nested',
234 });
235
236 expect(status).toBe(400);
237 });
238});
tests/page.load.test.js +52 −1
@@ -15,6 +15,7 @@ describe('page load smoke test', () =>
15 15 let rootsFixture;
16 16 let listFixture;
17 17 let spaceFixture;
18 let meFixture;
18 19
19 20 beforeEach(() =>
20 21 {
@@ -33,6 +34,7 @@ describe('page load smoke test', () =>
33 34 spaceFixture = {
34 35 '/data': { usedBytes: 0, freeBytes: 1024 * 1024 },
35 36 };
37 meFixture = { username: 'tester', isAdmin: false, permissions: {} };
36 38 });
37 39
38 40 beforeAll(async () =>
@@ -47,7 +49,7 @@ describe('page load smoke test', () =>
47 49
48 50 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
49 51 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
50 app.get('/api/auth/me', (req, res) => res.json({ username: 'tester', isAdmin: false, permissions: {} }));
52 app.get('/api/auth/me', (req, res) => res.json(meFixture));
51 53 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
52 54 app.get('/api/files/list', (req, res) =>
53 55 {
@@ -215,4 +217,53 @@ describe('page load smoke test', () =>
215 217
216 218 dom.window.close();
217 219 });
220
221 test('root sidebar shows alias and original name, and excludes Move to action', async () =>
222 {
223 rootsFixture = [
224 { label: 'Shared', path: '/data-a', originalName: 'data-a', alias: 'Shared' },
225 { label: 'Root B', path: '/data-b', originalName: 'data-b', alias: null },
226 ];
227 meFixture = {
228 username: 'tester',
229 isAdmin: false,
230 permissions: {
231 'data-a': { read: true, write: true },
232 'data-b': { read: true, write: false },
233 },
234 };
235 spaceFixture = {
236 '/data-a': { usedBytes: 1024, freeBytes: 2048 },
237 '/data-b': { usedBytes: 2048, freeBytes: 1024 },
238 };
239
240 const { dom, runtimeErrors } = await bootClient({
241 savedSession: {
242 token: 'saved-token',
243 dir: null,
244 rootPath: null,
245 lastOperationAt: Date.now(),
246 },
247 });
248
249 expect(runtimeErrors).toEqual([]);
250
251 const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]');
252 expect(rootTile).toBeTruthy();
253 rootTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
254 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
255
256 const sidebarText = dom.window.document.getElementById('sidebar-meta').textContent;
257 expect(sidebarText).toContain('Alias');
258 expect(sidebarText).toContain('Shared');
259 expect(sidebarText).toContain('Original name');
260 expect(sidebarText).toContain('data-a');
261
262 const actionButtons = Array.from(dom.window.document.querySelectorAll('#sidebar-actions button')).map(b => b.textContent);
263 expect(actionButtons).toContain('Rename');
264 expect(actionButtons).not.toContain('Move to');
265 expect(actionButtons).not.toContain('Delete');
266
267 dom.window.close();
268 });
218 269 });
@@ -15,6 +15,7 @@ describe('page load smoke test', () =>
15 let rootsFixture;
15 let rootsFixture;
16 let listFixture;
16 let listFixture;
17 let spaceFixture;
17 let spaceFixture;
18 let meFixture;
18
19
19 beforeEach(() =>
20 beforeEach(() =>
20 {
21 {
@@ -33,6 +34,7 @@ describe('page load smoke test', () =>
33 spaceFixture = {
34 spaceFixture = {
34 '/data': { usedBytes: 0, freeBytes: 1024 * 1024 },
35 '/data': { usedBytes: 0, freeBytes: 1024 * 1024 },
35 };
36 };
37 meFixture = { username: 'tester', isAdmin: false, permissions: {} };
36 });
38 });
37
39
38 beforeAll(async () =>
40 beforeAll(async () =>
@@ -47,7 +49,7 @@ describe('page load smoke test', () =>
47
49
48 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
50 app.get('/api/auth/server-key', (req, res) => res.json({ publicKey: null }));
49 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
51 app.get('/api/auth/setup-needed', (req, res) => res.json({ needed: false }));
50 app.get('/api/auth/me', (req, res) => res.json({ username: 'tester', isAdmin: false, permissions: {} }));
52 app.get('/api/auth/me', (req, res) => res.json(meFixture));
51 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
53 app.get('/api/files/roots', (req, res) => res.json({ roots: rootsFixture }));
52 app.get('/api/files/list', (req, res) =>
54 app.get('/api/files/list', (req, res) =>
53 {
55 {
@@ -215,4 +217,53 @@ describe('page load smoke test', () =>
215
217
216 dom.window.close();
218 dom.window.close();
217 });
219 });
220
221 test('root sidebar shows alias and original name, and excludes Move to action', async () =>
222 {
223 rootsFixture = [
224 { label: 'Shared', path: '/data-a', originalName: 'data-a', alias: 'Shared' },
225 { label: 'Root B', path: '/data-b', originalName: 'data-b', alias: null },
226 ];
227 meFixture = {
228 username: 'tester',
229 isAdmin: false,
230 permissions: {
231 'data-a': { read: true, write: true },
232 'data-b': { read: true, write: false },
233 },
234 };
235 spaceFixture = {
236 '/data-a': { usedBytes: 1024, freeBytes: 2048 },
237 '/data-b': { usedBytes: 2048, freeBytes: 1024 },
238 };
239
240 const { dom, runtimeErrors } = await bootClient({
241 savedSession: {
242 token: 'saved-token',
243 dir: null,
244 rootPath: null,
245 lastOperationAt: Date.now(),
246 },
247 });
248
249 expect(runtimeErrors).toEqual([]);
250
251 const rootTile = dom.window.document.querySelector('.file-item[data-path="/data-a"]');
252 expect(rootTile).toBeTruthy();
253 rootTile.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
254 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
255
256 const sidebarText = dom.window.document.getElementById('sidebar-meta').textContent;
257 expect(sidebarText).toContain('Alias');
258 expect(sidebarText).toContain('Shared');
259 expect(sidebarText).toContain('Original name');
260 expect(sidebarText).toContain('data-a');
261
262 const actionButtons = Array.from(dom.window.document.querySelectorAll('#sidebar-actions button')).map(b => b.textContent);
263 expect(actionButtons).toContain('Rename');
264 expect(actionButtons).not.toContain('Move to');
265 expect(actionButtons).not.toContain('Delete');
266
267 dom.window.close();
268 });
218});
269});