BlueGit

timfa filemanager

fixes and updates

timfa Tim Falken · pushed by timfa

Authored 2026-05-03 · 6 months ago

Hash
0ae63c843f32ef5791f3f1b80e1fc27c135a1f15
Parent
522f0db3
14 files changed +1650 −828
.github/copilot-instructions.md added +30 −0
@@ -0,0 +1,30 @@
1 # AI Coding Agent Instructions for Filemanager
2
3 ## Architecture Essentials
4
5 ### Technical Specifications
6 - For every file and implementation, log the file and all of its classes and functions in `.github/technical-reference.md`
7 - When functionality is modified or added, update that file.
8 - Reference the file before making changes to ensure no duplicate functionality is made
9 - the file serves as an index and reference for the code architecture, as well as individual classes and methods.
10 - Keep it short and specific; no paragraphs of explanation, only a simple notation of a file, class or method and a one-line description of what it does, what it should be used for, and what to keep into account when using it.
11 - `.github/tests.md` is an index of every test file and every test name inside it. Keep it up to date whenever tests are added, removed, or renamed. Reference it to understand existing coverage before deciding whether to add a new test.
12
13
14 ## Developer Workflows
15
16 ### Git authoring
17 - When starting work on something, create a feature or fix branch
18 - When concrete, complete steps are made, create a commit in that branch
19 - When all work is done, merge the branch into master, and then delete it so only master remains
20 - Ensure you don't leave old branches you've made in git and that everything is merged neatly.
21 - Always run the full test suite and fix any issues before merging to master.
22
23 ## Testing Expectations
24 - **Default rule:** every new feature should receive a test that verifies it behaves as requested.
25 - If a very similar test already exists, expand or adapt that test instead of creating duplicate coverage.
26 - When a change affects an area that existing tests are meant to cover, update those tests so the new behavior is validated too.
27 - After modifying any function or module, check `tests.md` for tests that exercise that code path — directly or indirectly — and verify those tests still reflect the current behavior. If they no longer do, update them before finishing.
28 - When encountering existing functionality that is not covered by tests, automatically add coverage for it unless it is extremely simple; for extremely simple cases, ask the user first before skipping the test.
29 - Only skip adding a test, or ask the user first, when the change is truly tiny or not behaviorally meaningful (for example: wording-only copy edits, comments, or other negligible changes).
30 - Prefer reusing production helpers and real code paths in tests rather than duplicating business logic in test-only code.
@@ -0,0 +1,30 @@
1# AI Coding Agent Instructions for Filemanager
2
3## Architecture Essentials
4
5### Technical Specifications
6- For every file and implementation, log the file and all of its classes and functions in `.github/technical-reference.md`
7- When functionality is modified or added, update that file.
8- Reference the file before making changes to ensure no duplicate functionality is made
9- the file serves as an index and reference for the code architecture, as well as individual classes and methods.
10- Keep it short and specific; no paragraphs of explanation, only a simple notation of a file, class or method and a one-line description of what it does, what it should be used for, and what to keep into account when using it.
11- `.github/tests.md` is an index of every test file and every test name inside it. Keep it up to date whenever tests are added, removed, or renamed. Reference it to understand existing coverage before deciding whether to add a new test.
12
13
14## Developer Workflows
15
16### Git authoring
17- When starting work on something, create a feature or fix branch
18- When concrete, complete steps are made, create a commit in that branch
19- When all work is done, merge the branch into master, and then delete it so only master remains
20- Ensure you don't leave old branches you've made in git and that everything is merged neatly.
21- Always run the full test suite and fix any issues before merging to master.
22
23## Testing Expectations
24- **Default rule:** every new feature should receive a test that verifies it behaves as requested.
25- If a very similar test already exists, expand or adapt that test instead of creating duplicate coverage.
26- When a change affects an area that existing tests are meant to cover, update those tests so the new behavior is validated too.
27- After modifying any function or module, check `tests.md` for tests that exercise that code path — directly or indirectly — and verify those tests still reflect the current behavior. If they no longer do, update them before finishing.
28- When encountering existing functionality that is not covered by tests, automatically add coverage for it unless it is extremely simple; for extremely simple cases, ask the user first before skipping the test.
29- Only skip adding a test, or ask the user first, when the change is truly tiny or not behaviorally meaningful (for example: wording-only copy edits, comments, or other negligible changes).
30- Prefer reusing production helpers and real code paths in tests rather than duplicating business logic in test-only code.
.github/tests.md added +37 −0
@@ -0,0 +1,37 @@
1 # Test Index
2
3 > Auto-generated by `scripts/generate-tests-md.js`. Do not edit by hand.
4 > Run `node scripts/generate-tests-md.js` to regenerate.
5
6 ---
7
8 ## `test/admin.routes.test.js`
9 - `GET /api/admin/users`
10 - `POST /api/admin/users`
11 - `PATCH /api/admin/users/:id`
12 - `DELETE /api/admin/users/:id`
13 - `GET /api/admin/config`
14 - `PUT /api/admin/config`
15
16 ---
17
18 ## `test/auth.routes.test.js`
19 - `GET /api/auth/server-key`
20 - `GET /api/auth/setup-needed`
21 - `POST /api/auth/setup`
22 - `POST /api/auth/login`
23 - `session lifecycle / POST /api/auth/logout revokes active session`
24 - `session lifecycle / session expires after 1 hour of inactivity`
25
26 ---
27
28 ## `test/config.test.js`
29 - `getEffectivePaths`
30 - `getAllowedRoot`
31
32 ---
33
34 ## `test/crypto.test.js`
35 - `hybrid encrypt / decrypt round-trip`
36
37 ---
@@ -0,0 +1,37 @@
1# Test Index
2
3> Auto-generated by `scripts/generate-tests-md.js`. Do not edit by hand.
4> Run `node scripts/generate-tests-md.js` to regenerate.
5
6---
7
8## `test/admin.routes.test.js`
9- `GET /api/admin/users`
10- `POST /api/admin/users`
11- `PATCH /api/admin/users/:id`
12- `DELETE /api/admin/users/:id`
13- `GET /api/admin/config`
14- `PUT /api/admin/config`
15
16---
17
18## `test/auth.routes.test.js`
19- `GET /api/auth/server-key`
20- `GET /api/auth/setup-needed`
21- `POST /api/auth/setup`
22- `POST /api/auth/login`
23- `session lifecycle / POST /api/auth/logout revokes active session`
24- `session lifecycle / session expires after 1 hour of inactivity`
25
26---
27
28## `test/config.test.js`
29- `getEffectivePaths`
30- `getAllowedRoot`
31
32---
33
34## `test/crypto.test.js`
35- `hybrid encrypt / decrypt round-trip`
36
37---
public/app.js +533 −321
@@ -13,14 +13,14 @@
13 13 // STATE
14 14 // ───────────────────────────────────────────────────────────────────────────
15 15 const STATE = {
16 token: null, // decrypted JWT string
17 username: null,
18 isAdmin: false,
19 permissions: {},
20 roots: [], // [{ label, path }]
21 currentDir: null, // absolute path currently shown (null = roots view)
22 currentRoot: null, // { label, path } of the active root
23 items: [], // current directory listing
16 token: null, // decrypted JWT string
17 username: null,
18 isAdmin: false,
19 permissions: {},
20 roots: [], // [{ label, path }]
21 currentDir: null, // absolute path currently shown (null = roots view)
22 currentRoot: null, // { label, path } of the active root
23 items: [], // current directory listing
24 24 selectedItem: null, // item object selected in sidebar
25 25
26 26 // Ephemeral key pair per session (client-side)
@@ -51,14 +51,15 @@ const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
51 51 // CRYPTO HELPERS (Web Crypto API)
52 52 // ───────────────────────────────────────────────────────────────────────────
53 53
54 async function generateClientKeyPair() {
54 async function generateClientKeyPair ()
55 {
55 56 if (!hasWebCrypto()) return;
56 57 const kp = await crypto.subtle.generateKey(
57 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' },
58 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
58 59 true,
59 60 ['encrypt', 'decrypt'],
60 61 );
61 STATE.clientPrivateKey = kp.privateKey;
62 STATE.clientPrivateKey = kp.privateKey;
62 63 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
63 64 }
64 65
@@ -66,8 +67,10 @@ async function generateClientKeyPair() {
66 67 * Hybrid-encrypt a JS object using the server's RSA public key.
67 68 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
68 69 */
69 async function hybridEncryptForServer(obj) {
70 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) {
70 async function hybridEncryptForServer (obj)
71 {
72 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
73 {
71 74 return { plaintext: obj };
72 75 }
73 76
@@ -77,39 +80,40 @@ async function hybridEncryptForServer(obj) {
77 80 false, ['encrypt'],
78 81 );
79 82
80 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
81 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
82 const iv = crypto.getRandomValues(new Uint8Array(12));
83 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
83 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
84 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
85 const iv = crypto.getRandomValues(new Uint8Array(12));
86 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
84 87
85 88 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
86 const gcmBytes = new Uint8Array(gcmResult);
89 const gcmBytes = new Uint8Array(gcmResult);
87 90 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
88 const tag = gcmBytes.slice(gcmBytes.length - 16);
91 const tag = gcmBytes.slice(gcmBytes.length - 16);
89 92
90 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
91 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
93 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
94 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
92 95
93 96 return {
94 97 encryptedKey: b64(encryptedKey),
95 iv: b64(iv),
96 ciphertext: b64(ciphertext),
97 tag: b64(tag),
98 iv: b64(iv),
99 ciphertext: b64(ciphertext),
100 tag: b64(tag),
98 101 };
99 102 }
100 103
101 104 /**
102 105 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
103 106 */
104 async function hybridDecryptFromServer(payload) {
107 async function hybridDecryptFromServer (payload)
108 {
105 109 if (!payload) return null;
106 110 if (payload.token) return payload.token;
107 111 if (!hasWebCrypto()) return null;
108 112
109 const encryptedKey = unb64(payload.encryptedKey);
110 const iv = unb64(payload.iv);
111 const ciphertext = unb64(payload.ciphertext);
112 const tag = unb64(payload.tag);
113 const encryptedKey = unb64(payload.encryptedKey);
114 const iv = unb64(payload.iv);
115 const ciphertext = unb64(payload.ciphertext);
116 const tag = unb64(payload.tag);
113 117
114 118 const rawAes = await crypto.subtle.decrypt(
115 119 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
@@ -130,23 +134,27 @@ async function hybridDecryptFromServer(payload) {
130 134 // UTIL
131 135 // ───────────────────────────────────────────────────────────────────────────
132 136
133 function b64(buf) {
137 function b64 (buf)
138 {
134 139 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
135 140 }
136 141
137 function hasWebCrypto() {
142 function hasWebCrypto ()
143 {
138 144 return !!(window.crypto && window.crypto.subtle);
139 145 }
140 146
141 function unb64(str) {
147 function unb64 (str)
148 {
142 149 const binary = atob(str);
143 const buf = new Uint8Array(binary.length);
150 const buf = new Uint8Array(binary.length);
144 151 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
145 152 return buf.buffer;
146 153 }
147 154
148 155 /** Stable browser fingerprint (not stored, derived fresh each load) */
149 function getFingerprint() {
156 function getFingerprint ()
157 {
150 158 const binding = getOrCreateClientBindingId();
151 159 const nav = navigator;
152 160
@@ -161,35 +169,44 @@ function getFingerprint() {
161 169 ].join('|');
162 170 }
163 171
164 function randomIdHex(bytes = 16) {
172 function randomIdHex (bytes = 16)
173 {
165 174 const arr = new Uint8Array(bytes);
166 if (window.crypto && typeof window.crypto.getRandomValues === 'function') {
175 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
176 {
167 177 window.crypto.getRandomValues(arr);
168 } else {
178 } else
179 {
169 180 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
170 181 }
171 182 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
172 183 }
173 184
174 function getOrCreateClientBindingId() {
185 function getOrCreateClientBindingId ()
186 {
175 187 if (STATE.clientBindingId) return STATE.clientBindingId;
176 188
177 try {
189 try
190 {
178 191 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
179 if (existing && typeof existing === 'string') {
192 if (existing && typeof existing === 'string')
193 {
180 194 STATE.clientBindingId = existing;
181 195 return existing;
182 196 }
183 } catch {
197 } catch
198 {
184 199 // Ignore storage read errors.
185 200 }
186 201
187 202 const created = randomIdHex(16);
188 203 STATE.clientBindingId = created;
189 204
190 try {
205 try
206 {
191 207 localStorage.setItem(CLIENT_BINDING_KEY, created);
192 } catch {
208 } catch
209 {
193 210 // Ignore storage write errors; in-memory fallback still keeps this stable
194 211 // for the current page session.
195 212 }
@@ -197,42 +214,49 @@ function getOrCreateClientBindingId() {
197 214 return created;
198 215 }
199 216
200 function formatBytes(bytes) {
217 function formatBytes (bytes)
218 {
201 219 if (bytes == null) return '—';
202 if (bytes < 1024) return bytes + ' B';
203 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
204 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
220 if (bytes < 1024) return bytes + ' B';
221 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
222 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
205 223 return (bytes / 1073741824).toFixed(2) + ' GB';
206 224 }
207 225
208 function extOf(name) {
226 function extOf (name)
227 {
209 228 const i = name.lastIndexOf('.');
210 229 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
211 230 }
212 231
213 function getPathSep(basePath) {
232 function getPathSep (basePath)
233 {
214 234 return basePath && basePath.includes('\\') ? '\\' : '/';
215 235 }
216 236
217 function joinServerPath(basePath, segment) {
237 function joinServerPath (basePath, segment)
238 {
218 239 const sep = getPathSep(basePath);
219 240 const base = String(basePath || '').replace(/[\\/]+$/, '');
220 241 return base + sep + segment;
221 242 }
222 243
223 function samePath(a, b) {
244 function samePath (a, b)
245 {
224 246 if (!a || !b) return false;
225 247 return String(a).toLowerCase() === String(b).toLowerCase();
226 248 }
227 249
228 function pathInside(child, root) {
250 function pathInside (child, root)
251 {
229 252 if (!child || !root) return false;
230 253 if (samePath(child, root)) return true;
231 254 const sep = getPathSep(root);
232 255 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
233 256 }
234 257
235 function saveSessionState() {
258 function saveSessionState ()
259 {
236 260 if (!STATE.token) return;
237 261 const now = Date.now();
238 262 STATE.lastOperationAt = now;
@@ -242,33 +266,40 @@ function saveSessionState() {
242 266 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
243 267 lastOperationAt: STATE.lastOperationAt,
244 268 };
245 try {
269 try
270 {
246 271 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
247 } catch {
272 } catch
273 {
248 274 // Ignore storage errors (private mode/full quota).
249 275 }
250 276 }
251 277
252 function loadSessionState() {
253 try {
278 function loadSessionState ()
279 {
280 try
281 {
254 282 const raw = localStorage.getItem(SESSION_KEY);
255 283 if (!raw) return null;
256 284 const parsed = JSON.parse(raw);
257 285 if (!parsed || typeof parsed.token !== 'string') return null;
258 286 if (!Number.isFinite(parsed.lastOperationAt)) return null;
259 287
260 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) {
288 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
289 {
261 290 clearSessionState();
262 291 return null;
263 292 }
264 293
265 294 return parsed;
266 } catch {
295 } catch
296 {
267 297 return null;
268 298 }
269 299 }
270 300
271 function clearSessionState() {
301 function clearSessionState ()
302 {
272 303 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
273 304 }
274 305
@@ -276,12 +307,14 @@ function clearSessionState() {
276 307 // API
277 308 // ───────────────────────────────────────────────────────────────────────────
278 309
279 async function api(method, path, body, opts = {}) {
310 async function api (method, path, body, opts = {})
311 {
280 312 const headers = { 'Content-Type': 'application/json' };
281 313 const noAutoLogout = !!opts.noAutoLogout;
282 if (STATE.token) {
314 if (STATE.token)
315 {
283 316 headers['Authorization'] = 'Bearer ' + STATE.token;
284 headers['X-Fp'] = getFingerprint();
317 headers['X-Fp'] = getFingerprint();
285 318 }
286 319 const fetchOpts = { ...opts };
287 320 delete fetchOpts.noAutoLogout;
@@ -291,16 +324,19 @@ async function api(method, path, body, opts = {}) {
291 324 body: body != null ? JSON.stringify(body) : undefined,
292 325 ...fetchOpts,
293 326 });
294 if (!res.ok) {
327 if (!res.ok)
328 {
295 329 const j = await res.json().catch(() => ({}));
296 330 // Session-expired → force re-login
297 if (res.status === 401) {
331 if (res.status === 401)
332 {
298 333 if (!noAutoLogout) logout();
299 334 return null;
300 335 }
301 336 throw new Error(j.error || res.statusText);
302 337 }
303 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) {
338 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
339 {
304 340 saveSessionState();
305 341 }
306 342 return res.json();
@@ -310,7 +346,8 @@ async function api(method, path, body, opts = {}) {
310 346 // TOAST
311 347 // ───────────────────────────────────────────────────────────────────────────
312 348
313 function toast(msg, type = '') {
349 function toast (msg, type = '')
350 {
314 351 const el = document.createElement('div');
315 352 el.className = 'toast-msg' + (type ? ' ' + type : '');
316 353 el.textContent = msg;
@@ -328,24 +365,27 @@ function toast(msg, type = '') {
328 365 * @param {string} message
329 366 * @returns {Promise<boolean>} true = OK, false = Cancel
330 367 */
331 function showConfirm(title, message) {
332 return new Promise((resolve) => {
368 function showConfirm (title, message)
369 {
370 return new Promise((resolve) =>
371 {
333 372 const overlay = document.getElementById('confirm-modal');
334 document.getElementById('confirm-modal-title').textContent = title;
373 document.getElementById('confirm-modal-title').textContent = title;
335 374 document.getElementById('confirm-modal-message').textContent = message;
336 375 overlay.classList.remove('hidden');
337 376
338 const ok = document.getElementById('confirm-modal-ok');
377 const ok = document.getElementById('confirm-modal-ok');
339 378 const cancel = document.getElementById('confirm-modal-cancel');
340 379
341 function finish(result) {
380 function finish (result)
381 {
342 382 overlay.classList.add('hidden');
343 383 ok.removeEventListener('click', onOk);
344 384 cancel.removeEventListener('click', onCancel);
345 385 resolve(result);
346 386 }
347 function onOk() { finish(true); }
348 function onCancel() { finish(false); }
387 function onOk () { finish(true); }
388 function onCancel () { finish(false); }
349 389
350 390 ok.addEventListener('click', onOk);
351 391 cancel.addEventListener('click', onCancel);
@@ -360,14 +400,16 @@ function showConfirm(title, message) {
360 400 * @param {string} [defaultValue] — pre-filled value
361 401 * @returns {Promise<string|null>} string = submitted value, null = cancelled
362 402 */
363 function showPrompt(title, message = '', defaultValue = '') {
364 return new Promise((resolve) => {
403 function showPrompt (title, message = '', defaultValue = '')
404 {
405 return new Promise((resolve) =>
406 {
365 407 const overlay = document.getElementById('prompt-modal');
366 const msgEl = document.getElementById('prompt-modal-message');
367 const input = document.getElementById('prompt-modal-input');
408 const msgEl = document.getElementById('prompt-modal-message');
409 const input = document.getElementById('prompt-modal-input');
368 410 const errorEl = document.getElementById('prompt-modal-error');
369 const form = document.getElementById('prompt-modal-form');
370 const cancel = document.getElementById('prompt-modal-cancel');
411 const form = document.getElementById('prompt-modal-form');
412 const cancel = document.getElementById('prompt-modal-cancel');
371 413
372 414 document.getElementById('prompt-modal-title').textContent = title;
373 415 msgEl.textContent = message;
@@ -378,17 +420,19 @@ function showPrompt(title, message = '', defaultValue = '') {
378 420 input.focus();
379 421 input.select();
380 422
381 function finish(result) {
423 function finish (result)
424 {
382 425 overlay.classList.add('hidden');
383 426 form.removeEventListener('submit', onSubmit);
384 427 cancel.removeEventListener('click', onCancel);
385 428 resolve(result);
386 429 }
387 function onSubmit(e) {
430 function onSubmit (e)
431 {
388 432 e.preventDefault();
389 433 finish(input.value);
390 434 }
391 function onCancel() { finish(null); }
435 function onCancel () { finish(null); }
392 436
393 437 form.addEventListener('submit', onSubmit);
394 438 cancel.addEventListener('click', onCancel);
@@ -400,18 +444,21 @@ function showPrompt(title, message = '', defaultValue = '') {
400 444 * @param {string} filename
401 445 * @returns {Promise<'yes'|'no'|'all'|'none'>}
402 446 */
403 function showOverwrite(filename) {
404 return new Promise((resolve) => {
447 function showOverwrite (filename)
448 {
449 return new Promise((resolve) =>
450 {
405 451 const overlay = document.getElementById('overwrite-modal');
406 452 document.getElementById('overwrite-modal-filename').textContent = filename;
407 453 overlay.classList.remove('hidden');
408 454
409 const btnYes = document.getElementById('overwrite-modal-yes');
410 const btnNo = document.getElementById('overwrite-modal-no');
411 const btnAll = document.getElementById('overwrite-modal-all');
455 const btnYes = document.getElementById('overwrite-modal-yes');
456 const btnNo = document.getElementById('overwrite-modal-no');
457 const btnAll = document.getElementById('overwrite-modal-all');
412 458 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
413 459
414 function finish(result) {
460 function finish (result)
461 {
415 462 overlay.classList.add('hidden');
416 463 btnYes.removeEventListener('click', onYes);
417 464 btnNo.removeEventListener('click', onNo);
@@ -419,10 +466,10 @@ function showOverwrite(filename) {
419 466 btnSkipAll.removeEventListener('click', onSkipAll);
420 467 resolve(result);
421 468 }
422 function onYes() { finish('yes'); }
423 function onNo() { finish('no'); }
424 function onAll() { finish('all'); }
425 function onSkipAll() { finish('none'); }
469 function onYes () { finish('yes'); }
470 function onNo () { finish('no'); }
471 function onAll () { finish('all'); }
472 function onSkipAll () { finish('none'); }
426 473
427 474 btnYes.addEventListener('click', onYes);
428 475 btnNo.addEventListener('click', onNo);
@@ -436,7 +483,8 @@ function showOverwrite(filename) {
436 483 // AUTH FLOW
437 484 // ───────────────────────────────────────────────────────────────────────────
438 485
439 function showAuthOverlay(setupMode = false) {
486 function showAuthOverlay (setupMode = false)
487 {
440 488 document.getElementById('app').classList.add('hidden');
441 489 const overlay = document.getElementById('auth-overlay');
442 490 overlay.classList.remove('hidden');
@@ -452,16 +500,19 @@ function showAuthOverlay(setupMode = false) {
452 500 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
453 501 }
454 502
455 function showApp() {
503 function showApp ()
504 {
456 505 document.getElementById('auth-overlay').classList.add('hidden');
457 506 document.getElementById('app').classList.remove('hidden');
458 507 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
459 508 startAutoRefresh();
460 509 }
461 510
462 async function initAuth() {
511 async function initAuth ()
512 {
463 513 // Always generate a fresh key pair so each page-load session is independent
464 await generateClientKeyPair().catch(() => {
514 await generateClientKeyPair().catch(() =>
515 {
465 516 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
466 517 });
467 518
@@ -474,16 +525,19 @@ async function initAuth() {
474 525 // Check whether first-run setup is needed
475 526 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
476 527
477 if (!needed) {
528 if (!needed)
529 {
478 530 const saved = loadSessionState();
479 if (saved && saved.token) {
531 if (saved && saved.token)
532 {
480 533 STATE.token = saved.token;
481 534 STATE.restoreDir = saved.dir || null;
482 535 STATE.restoreRootPath = saved.rootPath || null;
483 536 STATE.lastOperationAt = saved.lastOperationAt;
484 537
485 538 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
486 if (me) {
539 if (me)
540 {
487 541 STATE.username = me.username;
488 542 STATE.isAdmin = me.isAdmin;
489 543 STATE.permissions = me.permissions;
@@ -503,18 +557,21 @@ async function initAuth() {
503 557 showAuthOverlay(needed);
504 558 }
505 559
506 async function doLogin(username, password, isSetup) {
560 async function doLogin (username, password, isSetup)
561 {
507 562 const encrypted = await hybridEncryptForServer({ username, password });
508 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
563 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
509 564
510 565 let data;
511 try {
566 try
567 {
512 568 data = await api('POST', endpoint, {
513 569 encrypted,
514 570 clientPublicKey: STATE.clientPublicKeyJwk,
515 fingerprint: getFingerprint(),
571 fingerprint: getFingerprint(),
516 572 });
517 } catch (err) {
573 } catch (err)
574 {
518 575 return err.message;
519 576 }
520 577
@@ -529,8 +586,8 @@ async function doLogin(username, password, isSetup) {
529 586 const me = await api('GET', '/auth/me');
530 587 if (!me) return 'Session error.';
531 588
532 STATE.username = me.username;
533 STATE.isAdmin = me.isAdmin;
589 STATE.username = me.username;
590 STATE.isAdmin = me.isAdmin;
534 591 STATE.permissions = me.permissions;
535 592
536 593 saveSessionState();
@@ -539,29 +596,34 @@ async function doLogin(username, password, isSetup) {
539 596 return null; // no error
540 597 }
541 598
542 function logout() {
599 function logout ()
600 {
543 601 void performLogout();
544 602 }
545 603
546 async function performLogout() {
604 async function performLogout ()
605 {
547 606 const tokenAtStart = STATE.token;
548 607 stopAutoRefresh();
549 608
550 if (tokenAtStart) {
551 try {
609 if (tokenAtStart)
610 {
611 try
612 {
552 613 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
553 } catch {
614 } catch
615 {
554 616 // Ignore network errors while logging out locally.
555 617 }
556 618 }
557 619
558 STATE.token = null;
559 STATE.username = null;
560 STATE.isAdmin = false;
620 STATE.token = null;
621 STATE.username = null;
622 STATE.isAdmin = false;
561 623 STATE.permissions = {};
562 STATE.currentDir = null;
624 STATE.currentDir = null;
563 625 STATE.currentRoot = null;
564 STATE.items = [];
626 STATE.items = [];
565 627 STATE.restoreDir = null;
566 628 STATE.restoreRootPath = null;
567 629 STATE.lastOperationAt = null;
@@ -574,7 +636,8 @@ async function performLogout() {
574 636 // NAVIGATION
575 637 // ───────────────────────────────────────────────────────────────────────────
576 638
577 async function loadRoots(opts = {}) {
639 async function loadRoots (opts = {})
640 {
578 641 const data = await api('GET', '/files/roots');
579 642 if (!data) return;
580 643 STATE.roots = data.roots;
@@ -582,28 +645,35 @@ async function loadRoots(opts = {}) {
582 645 const preferredDir = opts.preferredDir || null;
583 646 const preferredRootPath = opts.preferredRootPath || null;
584 647
585 if (preferredDir && preferredRootPath) {
648 if (preferredDir && preferredRootPath)
649 {
586 650 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
587 if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) {
588 try {
651 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
652 {
653 try
654 {
589 655 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
590 656 return;
591 } catch {
657 } catch
658 {
592 659 // Fall back to default root behavior.
593 660 }
594 661 }
595 662 }
596 663
597 if (STATE.roots.length === 1) {
664 if (STATE.roots.length === 1)
665 {
598 666 // Single root → open it directly
599 667 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
600 } else {
668 } else
669 {
601 670 renderRootsView();
602 671 }
603 672 }
604 673
605 function renderRootsView() {
606 STATE.currentDir = null;
674 function renderRootsView ()
675 {
676 STATE.currentDir = null;
607 677 STATE.currentRoot = null;
608 678 saveSessionState();
609 679 renderBreadcrumb();
@@ -613,13 +683,15 @@ function renderRootsView() {
613 683 document.getElementById('folder-stats').classList.add('hidden');
614 684 closeSidebar();
615 685
616 for (const root of STATE.roots) {
686 for (const root of STATE.roots)
687 {
617 688 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
618 689 grid.appendChild(el);
619 690 }
620 691 }
621 692
622 async function navigateTo(absPath, root, opts = {}) {
693 async function navigateTo (absPath, root, opts = {})
694 {
623 695 if (root) STATE.currentRoot = root;
624 696 STATE.currentDir = absPath;
625 697
@@ -634,7 +706,8 @@ async function navigateTo(absPath, root, opts = {}) {
634 706 if (!opts.keepSidebar) closeSidebar();
635 707 }
636 708
637 function renderBreadcrumb() {
709 function renderBreadcrumb ()
710 {
638 711 const nav = document.getElementById('breadcrumb');
639 712 nav.innerHTML = '';
640 713
@@ -642,10 +715,13 @@ function renderBreadcrumb() {
642 715 const home = document.createElement('span');
643 716 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
644 717 home.textContent = 'Home';
645 home.addEventListener('click', () => {
646 if (STATE.roots.length === 1) {
718 home.addEventListener('click', () =>
719 {
720 if (STATE.roots.length === 1)
721 {
647 722 navigateTo(STATE.roots[0].path, STATE.roots[0]);
648 } else {
723 } else
724 {
649 725 renderRootsView();
650 726 }
651 727 });
@@ -654,15 +730,16 @@ function renderBreadcrumb() {
654 730 if (!STATE.currentDir || !STATE.currentRoot) return;
655 731
656 732 // Build path segments relative to the root
657 const rootPath = STATE.currentRoot.path;
658 const relative = STATE.currentDir === rootPath
733 const rootPath = STATE.currentRoot.path;
734 const relative = STATE.currentDir === rootPath
659 735 ? ''
660 736 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
661 737
662 738 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
663 739 let accumulated = rootPath;
664 740
665 for (let i = 0; i < parts.length; i++) {
741 for (let i = 0; i < parts.length; i++)
742 {
666 743 const sep = document.createElement('span');
667 744 sep.className = 'sep';
668 745 sep.textContent = ' / ';
@@ -674,7 +751,8 @@ function renderBreadcrumb() {
674 751
675 752 // Capture the path for this crumb
676 753 const capturedPath = i === 0 ? rootPath : accumulated;
677 if (i < parts.length - 1) {
754 if (i < parts.length - 1)
755 {
678 756 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
679 757 }
680 758
@@ -682,58 +760,68 @@ function renderBreadcrumb() {
682 760
683 761 // Advance accumulated path (skip for root label)
684 762 if (i > 0) accumulated = accumulated + '/' + parts[i];
685 else if (i === 0 && parts.length > 1) {
763 else if (i === 0 && parts.length > 1)
764 {
686 765 // After root label, next crumb should append the next segment
687 766 accumulated = rootPath;
688 767 }
689 768 }
690 769 }
691 770
692 async function refreshFolderStats() {
771 async function refreshFolderStats ()
772 {
693 773 const el = document.getElementById('folder-stats');
694 if (!STATE.currentDir) {
774 if (!STATE.currentDir)
775 {
695 776 el.classList.add('hidden');
696 777 return;
697 778 }
698 779
699 780 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
700 if (!data) {
781 if (!data)
782 {
701 783 el.classList.add('hidden');
702 784 return;
703 785 }
704 786
705 787 const used = formatBytes(data.usedBytes);
706 788 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
707 el.textContent = `Folder usage (recursive): ${used} | Free on root: ${free}`;
789 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
708 790 el.classList.remove('hidden');
709 791 }
710 792
711 function itemsSignature(items) {
793 function itemsSignature (items)
794 {
712 795 return JSON.stringify(
713 796 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
714 797 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
715 798 );
716 799 }
717 800
718 async function incrementalRefreshCurrentDir() {
801 async function incrementalRefreshCurrentDir ()
802 {
719 803 if (!STATE.currentDir || STATE.uploadInProgress) return;
720 804 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
721 805 if (!data) return;
722 806
723 807 const oldSig = itemsSignature(STATE.items);
724 808 const newSig = itemsSignature(data.items);
725 if (oldSig !== newSig) {
809 if (oldSig !== newSig)
810 {
726 811 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
727 812 STATE.items = data.items;
728 813 renderFileGrid();
729 814
730 if (selectedPath) {
815 if (selectedPath)
816 {
731 817 const match = STATE.items.find(i => i.path === selectedPath);
732 if (match) {
818 if (match)
819 {
733 820 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
734 821 .find(el => el.dataset.path === selectedPath);
735 822 if (selectedEl) selectItem(selectedEl, match);
736 } else {
823 } else
824 {
737 825 closeSidebar();
738 826 }
739 827 }
@@ -742,16 +830,20 @@ async function incrementalRefreshCurrentDir() {
742 830 await refreshFolderStats();
743 831 }
744 832
745 function startAutoRefresh() {
833 function startAutoRefresh ()
834 {
746 835 stopAutoRefresh();
747 STATE.autoRefreshTimer = setInterval(() => {
836 STATE.autoRefreshTimer = setInterval(() =>
837 {
748 838 if (document.hidden) return;
749 839 incrementalRefreshCurrentDir();
750 840 }, 5000);
751 841 }
752 842
753 function stopAutoRefresh() {
754 if (STATE.autoRefreshTimer) {
843 function stopAutoRefresh ()
844 {
845 if (STATE.autoRefreshTimer)
846 {
755 847 clearInterval(STATE.autoRefreshTimer);
756 848 STATE.autoRefreshTimer = null;
757 849 }
@@ -761,42 +853,48 @@ function stopAutoRefresh() {
761 853 // FILE GRID RENDERING
762 854 // ───────────────────────────────────────────────────────────────────────────
763 855
764 function renderFileGrid() {
856 function renderFileGrid ()
857 {
765 858 const grid = document.getElementById('file-grid');
766 859 grid.innerHTML = '';
767 860 const empty = document.getElementById('empty-notice');
768 861
769 const sorted = [...STATE.items].sort((a, b) => {
862 const sorted = [...STATE.items].sort((a, b) =>
863 {
770 864 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
771 865 return a.name.localeCompare(b.name);
772 866 });
773 867
774 868 empty.classList.toggle('hidden', sorted.length > 0);
775 869
776 for (const item of sorted) {
870 for (const item of sorted)
871 {
777 872 grid.appendChild(makeFileItem(item));
778 873 }
779 874 }
780 875
781 function makeFileItem(item) {
876 function makeFileItem (item)
877 {
782 878 const el = document.createElement('div');
783 879 el.className = 'file-item';
784 880 el.dataset.path = item.path;
785 881
786 882 const icon = document.createElement('div');
787 883 icon.className = 'icon';
788 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
884 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
789 885 el.appendChild(icon);
790 886
791 887 const name = document.createElement('div');
792 name.className = 'name';
888 name.className = 'name';
793 889 name.textContent = item.name;
794 890 el.appendChild(name);
795 891
796 892 // Single-click: open sidebar
797 el.addEventListener('click', (e) => {
893 el.addEventListener('click', (e) =>
894 {
798 895 e.stopPropagation();
799 if (item._root) {
896 if (item._root)
897 {
800 898 // Clicking a root tile goes straight in
801 899 navigateTo(item.path, item._root);
802 900 return;
@@ -805,11 +903,14 @@ function makeFileItem(item) {
805 903 });
806 904
807 905 // Double-click: enter folder or view/download file
808 el.addEventListener('dblclick', (e) => {
906 el.addEventListener('dblclick', (e) =>
907 {
809 908 e.stopPropagation();
810 if (item.isDir) {
909 if (item.isDir)
910 {
811 911 navigateTo(item.path, STATE.currentRoot);
812 } else {
912 } else
913 {
813 914 downloadOrView(item);
814 915 }
815 916 });
@@ -817,7 +918,8 @@ function makeFileItem(item) {
817 918 return el;
818 919 }
819 920
820 function selectItem(el, item) {
921 function selectItem (el, item)
922 {
821 923 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
822 924 el.classList.add('selected');
823 925 STATE.selectedItem = item;
@@ -828,7 +930,8 @@ function selectItem(el, item) {
828 930 // SIDEBAR
829 931 // ───────────────────────────────────────────────────────────────────────────
830 932
831 async function openSidebar(item) {
933 async function openSidebar (item)
934 {
832 935 const sidebar = document.getElementById('sidebar');
833 936 sidebar.classList.remove('hidden');
834 937 document.getElementById('app').classList.add('sidebar-open');
@@ -843,9 +946,11 @@ async function openSidebar(item) {
843 946 const actions = document.getElementById('sidebar-actions');
844 947 actions.innerHTML = '';
845 948
846 if (!item.isDir) {
949 if (!item.isDir)
950 {
847 951 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
848 if (meta) {
952 if (meta)
953 {
849 954 dl.innerHTML = `
850 955 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
851 956 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
@@ -859,7 +964,8 @@ async function openSidebar(item) {
859 964 btnDl.textContent = 'View / Download';
860 965 btnDl.addEventListener('click', () => downloadOrView(item));
861 966 actions.appendChild(btnDl);
862 } else {
967 } else
968 {
863 969 dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`;
864 970 const btnOpen = document.createElement('button');
865 971 btnOpen.textContent = 'Open folder';
@@ -868,7 +974,8 @@ async function openSidebar(item) {
868 974 }
869 975
870 976 // Rename button (write access required)
871 if (canWrite()) {
977 if (canWrite())
978 {
872 979 const btnRen = document.createElement('button');
873 980 btnRen.textContent = 'Rename';
874 981 btnRen.addEventListener('click', () => openRenameModal(item));
@@ -876,13 +983,14 @@ async function openSidebar(item) {
876 983
877 984 const btnDel = document.createElement('button');
878 985 btnDel.textContent = 'Delete';
879 btnDel.className = 'danger';
986 btnDel.className = 'danger';
880 987 btnDel.addEventListener('click', () => deleteItem(item));
881 988 actions.appendChild(btnDel);
882 989 }
883 990 }
884 991
885 function closeSidebar() {
992 function closeSidebar ()
993 {
886 994 document.getElementById('sidebar').classList.add('hidden');
887 995 document.getElementById('app').classList.remove('sidebar-open');
888 996 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
@@ -893,40 +1001,46 @@ function closeSidebar() {
893 1001 // DOWNLOAD / VIEW
894 1002 // ───────────────────────────────────────────────────────────────────────────
895 1003
896 function downloadOrView(item) {
1004 function downloadOrView (item)
1005 {
897 1006 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
898 1007 // Open in new tab — browser decides whether to display or download
899 const a = document.createElement('a');
900 a.href = url;
901 a.target = '_blank';
902 a.rel = 'noopener noreferrer';
1008 const a = document.createElement('a');
1009 a.href = url;
1010 a.target = '_blank';
1011 a.rel = 'noopener noreferrer';
903 1012 // We need to send the auth header; since <a> can't do that, we fetch and blob it
904 1013 fetchAndServe(item, url);
905 1014 }
906 1015
907 async function fetchAndServe(item, url) {
908 try {
1016 async function fetchAndServe (item, url)
1017 {
1018 try
1019 {
909 1020 const res = await fetch(url, {
910 1021 headers: {
911 1022 Authorization: 'Bearer ' + STATE.token,
912 'X-Fp': getFingerprint(),
1023 'X-Fp': getFingerprint(),
913 1024 },
914 1025 });
915 1026 if (!res.ok) { toast('Download failed.', 'err'); return; }
916 const blob = await res.blob();
917 const objUrl = URL.createObjectURL(blob);
918 const a = document.createElement('a');
919 a.href = objUrl;
920 a.download = item.name;
1027 const blob = await res.blob();
1028 const objUrl = URL.createObjectURL(blob);
1029 const a = document.createElement('a');
1030 a.href = objUrl;
1031 a.download = item.name;
921 1032 // Try to open viewable types inline
922 1033 const viewable = /^(image|video|audio|text|application\/pdf)/.test(blob.type);
923 if (viewable) {
1034 if (viewable)
1035 {
924 1036 window.open(objUrl, '_blank', 'noopener,noreferrer');
925 } else {
1037 } else
1038 {
926 1039 a.click();
927 1040 }
928 1041 setTimeout(() => URL.revokeObjectURL(objUrl), 60000);
929 } catch {
1042 } catch
1043 {
930 1044 toast('Download failed.', 'err');
931 1045 }
932 1046 }
@@ -935,16 +1049,18 @@ async function fetchAndServe(item, url) {
935 1049 // UPLOAD
936 1050 // ───────────────────────────────────────────────────────────────────────────
937 1051
938 function canWrite() {
1052 function canWrite ()
1053 {
939 1054 if (STATE.isAdmin) return true;
940 1055 if (!STATE.currentRoot) return false;
941 1056 const p = STATE.permissions[STATE.currentRoot.label];
942 1057 return p && p.write;
943 1058 }
944 1059
945 async function uploadFiles(fileList) {
1060 async function uploadFiles (fileList)
1061 {
946 1062 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
947 if (!canWrite()) { toast('No write access.', 'err'); return; }
1063 if (!canWrite()) { toast('No write access.', 'err'); return; }
948 1064
949 1065 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
950 1066 const formData = new FormData();
@@ -957,21 +1073,26 @@ async function uploadFiles(fileList) {
957 1073 document.body.appendChild(wrap);
958 1074 STATE.uploadInProgress = true;
959 1075
960 try {
1076 try
1077 {
961 1078 const xhr = new XMLHttpRequest();
962 1079 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
963 1080 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
964 1081 xhr.setRequestHeader('X-Fp', getFingerprint());
965 1082 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
966 1083
967 xhr.upload.addEventListener('progress', e => {
968 if (e.lengthComputable) {
1084 xhr.upload.addEventListener('progress', e =>
1085 {
1086 if (e.lengthComputable)
1087 {
969 1088 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
970 1089 }
971 1090 });
972 1091
973 await new Promise((resolve, reject) => {
974 xhr.onload = () => {
1092 await new Promise((resolve, reject) =>
1093 {
1094 xhr.onload = () =>
1095 {
975 1096 if (xhr.status === 200) resolve();
976 1097 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
977 1098 };
@@ -981,19 +1102,23 @@ async function uploadFiles(fileList) {
981 1102
982 1103 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
983 1104 await navigateTo(STATE.currentDir, STATE.currentRoot);
984 } catch (err) {
1105 } catch (err)
1106 {
985 1107 toast(err.message, 'err');
986 } finally {
1108 } finally
1109 {
987 1110 STATE.uploadInProgress = false;
988 1111 wrap.remove();
989 1112 }
990 1113 }
991 1114
992 async function uploadSingleFile(file, targetDir) {
1115 async function uploadSingleFile (file, targetDir)
1116 {
993 1117 const formData = new FormData();
994 1118 formData.append('files', file);
995 1119
996 await new Promise((resolve, reject) => {
1120 await new Promise((resolve, reject) =>
1121 {
997 1122 const xhr = new XMLHttpRequest();
998 1123 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
999 1124 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
@@ -1007,14 +1132,18 @@ async function uploadSingleFile(file, targetDir) {
1007 1132 });
1008 1133 }
1009 1134
1010 async function ensureServerDir(baseDir, relativeDir) {
1135 async function ensureServerDir (baseDir, relativeDir)
1136 {
1011 1137 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
1012 1138 let current = baseDir;
1013 for (const part of parts) {
1014 try {
1139 for (const part of parts)
1140 {
1141 try
1142 {
1015 1143 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
1016 1144 current = resp && resp.path ? resp.path : joinServerPath(current, part);
1017 } catch (err) {
1145 } catch (err)
1146 {
1018 1147 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1019 1148 current = joinServerPath(current, part);
1020 1149 }
@@ -1022,9 +1151,10 @@ async function ensureServerDir(baseDir, relativeDir) {
1022 1151 return current;
1023 1152 }
1024 1153
1025 async function uploadFolderInputFiles(fileList) {
1154 async function uploadFolderInputFiles (fileList)
1155 {
1026 1156 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1027 if (!canWrite()) { toast('No write access.', 'err'); return; }
1157 if (!canWrite()) { toast('No write access.', 'err'); return; }
1028 1158 if (!fileList || !fileList.length) return;
1029 1159
1030 1160 const files = Array.from(fileList);
@@ -1037,24 +1167,29 @@ async function uploadFolderInputFiles(fileList) {
1037 1167 document.body.appendChild(wrap);
1038 1168 STATE.uploadInProgress = true;
1039 1169
1040 try {
1170 try
1171 {
1041 1172 const dirCache = new Map();
1042 1173 dirCache.set('', STATE.currentDir);
1043 1174
1044 for (const file of files) {
1175 for (const file of files)
1176 {
1045 1177 const rel = file.webkitRelativePath || file.name;
1046 1178 const relParts = rel.split(/[\\/]/).filter(Boolean);
1047 1179 const relDir = relParts.slice(0, -1).join('/');
1048 1180
1049 if (!dirCache.has(relDir)) {
1181 if (!dirCache.has(relDir))
1182 {
1050 1183 const parentRel = relParts.slice(0, -2).join('/');
1051 1184 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
1052 1185 const thisName = relParts[relParts.length - 2];
1053 1186
1054 try {
1187 try
1188 {
1055 1189 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
1056 1190 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
1057 } catch (err) {
1191 } catch (err)
1192 {
1058 1193 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1059 1194 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
1060 1195 }
@@ -1069,9 +1204,11 @@ async function uploadFolderInputFiles(fileList) {
1069 1204
1070 1205 toast(`Uploaded ${total} file(s).`, 'ok');
1071 1206 await navigateTo(STATE.currentDir, STATE.currentRoot);
1072 } catch (err) {
1207 } catch (err)
1208 {
1073 1209 toast(err.message, 'err');
1074 } finally {
1210 } finally
1211 {
1075 1212 STATE.uploadInProgress = false;
1076 1213 wrap.remove();
1077 1214 }
@@ -1085,11 +1222,15 @@ async function uploadFolderInputFiles(fileList) {
1085 1222 * Reads all readEntries batches from a DirectoryReader (browsers may return
1086 1223 * results in chunks; we must keep calling until we get an empty array).
1087 1224 */
1088 function readAllEntries(reader) {
1089 return new Promise((resolve, reject) => {
1225 function readAllEntries (reader)
1226 {
1227 return new Promise((resolve, reject) =>
1228 {
1090 1229 const all = [];
1091 function next() {
1092 reader.readEntries(batch => {
1230 function next ()
1231 {
1232 reader.readEntries(batch =>
1233 {
1093 1234 if (!batch.length) { resolve(all); return; }
1094 1235 all.push(...batch);
1095 1236 next();
@@ -1103,17 +1244,22 @@ function readAllEntries(reader) {
1103 1244 * Recursively walk a FileSystemEntry tree, creating server-side directories
1104 1245 * on the fly and collecting { file, targetDir } pairs for upload.
1105 1246 */
1106 async function collectEntries(entry, serverDir, toUpload) {
1107 if (entry.isFile) {
1247 async function collectEntries (entry, serverDir, toUpload)
1248 {
1249 if (entry.isFile)
1250 {
1108 1251 const file = await new Promise((res, rej) => entry.file(res, rej));
1109 1252 toUpload.push({ file, targetDir: serverDir });
1110 } else if (entry.isDirectory) {
1253 } else if (entry.isDirectory)
1254 {
1111 1255 // Ask the server to create the directory; it returns the canonical path.
1112 1256 let newServerDir;
1113 try {
1257 try
1258 {
1114 1259 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
1115 1260 newServerDir = resp.path;
1116 } catch {
1261 } catch
1262 {
1117 1263 // Directory may already exist — reconstruct path from what we know.
1118 1264 // The server always returns JSON with {error} on failure, so we can
1119 1265 // still continue by falling back to a best-effort path join.
@@ -1124,15 +1270,17 @@ async function collectEntries(entry, serverDir, toUpload) {
1124 1270 }
1125 1271 const reader = entry.createReader();
1126 1272 const subEntries = await readAllEntries(reader);
1127 for (const sub of subEntries) {
1273 for (const sub of subEntries)
1274 {
1128 1275 await collectEntries(sub, newServerDir, toUpload);
1129 1276 }
1130 1277 }
1131 1278 }
1132 1279
1133 async function uploadEntries(entries) {
1280 async function uploadEntries (entries)
1281 {
1134 1282 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1135 if (!canWrite()) { toast('No write access.', 'err'); return; }
1283 if (!canWrite()) { toast('No write access.', 'err'); return; }
1136 1284
1137 1285 const wrap = document.createElement('div');
1138 1286 wrap.className = 'upload-bar-wrap';
@@ -1140,9 +1288,11 @@ async function uploadEntries(entries) {
1140 1288 document.body.appendChild(wrap);
1141 1289 STATE.uploadInProgress = true;
1142 1290
1143 try {
1291 try
1292 {
1144 1293 const toUpload = [];
1145 for (const entry of entries) {
1294 for (const entry of entries)
1295 {
1146 1296 await collectEntries(entry, STATE.currentDir, toUpload);
1147 1297 }
1148 1298
@@ -1150,13 +1300,15 @@ async function uploadEntries(entries) {
1150 1300
1151 1301 let done = 0;
1152 1302 const total = toUpload.length;
1153 const updateBar = () => {
1303 const updateBar = () =>
1304 {
1154 1305 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1155 1306 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1156 1307 };
1157 1308 updateBar();
1158 1309
1159 for (const { file, targetDir } of toUpload) {
1310 for (const { file, targetDir } of toUpload)
1311 {
1160 1312 await uploadSingleFile(file, targetDir);
1161 1313 done++;
1162 1314 updateBar();
@@ -1164,9 +1316,11 @@ async function uploadEntries(entries) {
1164 1316
1165 1317 toast(`Uploaded ${total} file(s).`, 'ok');
1166 1318 await navigateTo(STATE.currentDir, STATE.currentRoot);
1167 } catch (err) {
1319 } catch (err)
1320 {
1168 1321 toast(err.message, 'err');
1169 } finally {
1322 } finally
1323 {
1170 1324 STATE.uploadInProgress = false;
1171 1325 wrap.remove();
1172 1326 }
@@ -1175,22 +1329,26 @@ async function uploadEntries(entries) {
1175 1329 // DRAG-AND-DROP
1176 1330 // ───────────────────────────────────────────────────────────────────────────
1177 1331
1178 function initDragDrop() {
1179 const main = document.getElementById('main-content');
1332 function initDragDrop ()
1333 {
1334 const main = document.getElementById('main-content');
1180 1335 const dropOvl = document.getElementById('drop-overlay');
1181 1336 let dragDepth = 0;
1182 1337
1183 main.addEventListener('dragenter', e => {
1338 main.addEventListener('dragenter', e =>
1339 {
1184 1340 e.preventDefault();
1185 1341 dragDepth++;
1186 1342 dropOvl.classList.remove('hidden');
1187 1343 });
1188 main.addEventListener('dragleave', () => {
1344 main.addEventListener('dragleave', () =>
1345 {
1189 1346 dragDepth--;
1190 1347 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
1191 1348 });
1192 1349 main.addEventListener('dragover', e => e.preventDefault());
1193 main.addEventListener('drop', async e => {
1350 main.addEventListener('drop', async e =>
1351 {
1194 1352 e.preventDefault();
1195 1353 dragDepth = 0;
1196 1354 dropOvl.classList.add('hidden');
@@ -1198,9 +1356,11 @@ function initDragDrop() {
1198 1356
1199 1357 const items = Array.from(e.dataTransfer.items || []);
1200 1358 // Use the FileSystem Entry API when available so we can handle folders.
1201 if (items.length && typeof items[0].webkitGetAsEntry === 'function') {
1359 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
1360 {
1202 1361 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
1203 if (entries.some(en => en.isDirectory)) {
1362 if (entries.some(en => en.isDirectory))
1363 {
1204 1364 await uploadEntries(entries);
1205 1365 return;
1206 1366 }
@@ -1215,7 +1375,8 @@ function initDragDrop() {
1215 1375 // RENAME
1216 1376 // ───────────────────────────────────────────────────────────────────────────
1217 1377
1218 function openRenameModal(item) {
1378 function openRenameModal (item)
1379 {
1219 1380 const modal = document.getElementById('rename-modal');
1220 1381 modal.classList.remove('hidden');
1221 1382 const input = document.getElementById('rename-input');
@@ -1223,16 +1384,19 @@ function openRenameModal(item) {
1223 1384 input.focus();
1224 1385 input.select();
1225 1386 document.getElementById('rename-error').classList.add('hidden');
1226 document.getElementById('rename-form').onsubmit = async (e) => {
1387 document.getElementById('rename-form').onsubmit = async (e) =>
1388 {
1227 1389 e.preventDefault();
1228 1390 const newName = input.value.trim();
1229 1391 if (!newName) return;
1230 try {
1392 try
1393 {
1231 1394 await api('POST', '/files/rename', { from: item.path, to: newName });
1232 1395 modal.classList.add('hidden');
1233 1396 toast('Renamed.', 'ok');
1234 1397 await navigateTo(STATE.currentDir, STATE.currentRoot);
1235 } catch (err) {
1398 } catch (err)
1399 {
1236 1400 document.getElementById('rename-error').textContent = err.message;
1237 1401 document.getElementById('rename-error').classList.remove('hidden');
1238 1402 }
@@ -1243,14 +1407,17 @@ function openRenameModal(item) {
1243 1407 // DELETE
1244 1408 // ───────────────────────────────────────────────────────────────────────────
1245 1409
1246 async function deleteItem(item) {
1410 async function deleteItem (item)
1411 {
1247 1412 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
1248 try {
1413 try
1414 {
1249 1415 await api('POST', '/files/delete', { path: item.path });
1250 1416 toast('Deleted.', 'ok');
1251 1417 closeSidebar();
1252 1418 await navigateTo(STATE.currentDir, STATE.currentRoot);
1253 } catch (err) {
1419 } catch (err)
1420 {
1254 1421 toast(err.message, 'err');
1255 1422 }
1256 1423 }
@@ -1259,29 +1426,34 @@ async function deleteItem(item) {
1259 1426 // ADMIN PANEL
1260 1427 // ───────────────────────────────────────────────────────────────────────────
1261 1428
1262 async function openAdminModal() {
1429 async function openAdminModal ()
1430 {
1263 1431 document.getElementById('admin-modal').classList.remove('hidden');
1264 1432 await refreshAdminConfig();
1265 1433 await refreshAdminUsers();
1266 1434 }
1267 1435
1268 async function refreshAdminConfig() {
1436 async function refreshAdminConfig ()
1437 {
1269 1438 const data = await api('GET', '/admin/config');
1270 1439 if (!data) return;
1271 1440 const container = document.getElementById('admin-paths');
1272 1441 container.innerHTML = '';
1273 for (const p of data.paths) {
1442 for (const p of data.paths)
1443 {
1274 1444 const row = document.createElement('div');
1275 1445 row.className = 'path-row';
1276 1446 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
1277 row.querySelector('button').addEventListener('click', () => {
1447 row.querySelector('button').addEventListener('click', () =>
1448 {
1278 1449 row.remove();
1279 1450 });
1280 1451 container.appendChild(row);
1281 1452 }
1282 1453 }
1283 1454
1284 async function refreshAdminUsers() {
1455 async function refreshAdminUsers ()
1456 {
1285 1457 const data = await api('GET', '/admin/users');
1286 1458 if (!data) return;
1287 1459 const container = document.getElementById('admin-users-list');
@@ -1291,7 +1463,8 @@ async function refreshAdminUsers() {
1291 1463 const cfg = await api('GET', '/admin/config');
1292 1464 const paths = cfg ? (cfg.effectivePaths || []) : [];
1293 1465
1294 for (const u of data.users) {
1466 for (const u of data.users)
1467 {
1295 1468 const row = document.createElement('div');
1296 1469 row.className = 'user-row';
1297 1470 row.innerHTML = `
@@ -1302,9 +1475,11 @@ async function refreshAdminUsers() {
1302 1475 `;
1303 1476 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
1304 1477 openUserModal(u, paths));
1305 row.querySelector('[data-action="delete"]').addEventListener('click', async () => {
1478 row.querySelector('[data-action="delete"]').addEventListener('click', async () =>
1479 {
1306 1480 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
1307 try {
1481 try
1482 {
1308 1483 await api('DELETE', `/admin/users/${u.id}`);
1309 1484 toast('User deleted.', 'ok');
1310 1485 await refreshAdminUsers();
@@ -1314,17 +1489,18 @@ async function refreshAdminUsers() {
1314 1489 }
1315 1490 }
1316 1491
1317 function openUserModal(user, paths) {
1492 function openUserModal (user, paths)
1493 {
1318 1494 const modal = document.getElementById('user-modal');
1319 1495 modal.classList.remove('hidden');
1320 1496 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
1321 1497 document.getElementById('user-error').classList.add('hidden');
1322 1498
1323 1499 const usernameInput = document.getElementById('user-username');
1324 usernameInput.value = user ? user.username : '';
1500 usernameInput.value = user ? user.username : '';
1325 1501 usernameInput.readOnly = !!user;
1326 1502
1327 document.getElementById('user-password').value = '';
1503 document.getElementById('user-password').value = '';
1328 1504 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
1329 1505
1330 1506 // Password placeholder
@@ -1334,7 +1510,8 @@ function openUserModal(user, paths) {
1334 1510 // Build permissions grid
1335 1511 const permDiv = document.getElementById('user-permissions');
1336 1512 permDiv.innerHTML = '';
1337 if (paths.length) {
1513 if (paths.length)
1514 {
1338 1515 const heading = document.createElement('h4');
1339 1516 heading.textContent = 'Path Permissions';
1340 1517 permDiv.appendChild(heading);
@@ -1342,9 +1519,12 @@ function openUserModal(user, paths) {
1342 1519 const isAdminUser = !!(user && user.isAdmin);
1343 1520 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
1344 1521 const adminChk = document.getElementById('user-is-admin');
1345 const rebuildPermRows = (admin) => {
1346 permDiv.querySelectorAll('.perm-row').forEach(r => {
1347 r.querySelectorAll('input[type=checkbox]').forEach(cb => {
1522 const rebuildPermRows = (admin) =>
1523 {
1524 permDiv.querySelectorAll('.perm-row').forEach(r =>
1525 {
1526 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
1527 {
1348 1528 cb.disabled = admin;
1349 1529 if (admin) cb.checked = true;
1350 1530 });
@@ -1353,12 +1533,13 @@ function openUserModal(user, paths) {
1353 1533 };
1354 1534 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
1355 1535
1356 for (const p of paths) {
1357 const label = p.split(/[\\/]/).pop();
1358 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
1359 const row = document.createElement('div');
1536 for (const p of paths)
1537 {
1538 const label = p.split(/[\\/]/).pop();
1539 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
1540 const row = document.createElement('div');
1360 1541 row.className = 'perm-row';
1361 const readChecked = isAdminUser || perms.read;
1542 const readChecked = isAdminUser || perms.read;
1362 1543 const writeChecked = isAdminUser || perms.write;
1363 1544 row.innerHTML = `
1364 1545 <span class="perm-label">${label}</span>
@@ -1370,30 +1551,36 @@ function openUserModal(user, paths) {
1370 1551 }
1371 1552 }
1372 1553
1373 document.getElementById('user-form').onsubmit = async (e) => {
1554 document.getElementById('user-form').onsubmit = async (e) =>
1555 {
1374 1556 e.preventDefault();
1375 const password = document.getElementById('user-password').value;
1376 const isAdmin = document.getElementById('user-is-admin').checked;
1557 const password = document.getElementById('user-password').value;
1558 const isAdmin = document.getElementById('user-is-admin').checked;
1377 1559 const permissions = {};
1378 permDiv.querySelectorAll('input[data-label]').forEach(cb => {
1560 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
1561 {
1379 1562 const lbl = cb.dataset.label;
1380 1563 if (!permissions[lbl]) permissions[lbl] = {};
1381 1564 permissions[lbl][cb.dataset.type] = cb.checked;
1382 1565 });
1383 1566
1384 try {
1385 if (user) {
1567 try
1568 {
1569 if (user)
1570 {
1386 1571 const body = { isAdmin, permissions };
1387 1572 if (password) body.password = password;
1388 1573 await api('PATCH', `/admin/users/${user.id}`, body);
1389 } else {
1574 } else
1575 {
1390 1576 const uname = document.getElementById('user-username').value.trim();
1391 1577 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
1392 1578 }
1393 1579 modal.classList.add('hidden');
1394 1580 toast('User saved.', 'ok');
1395 1581 await refreshAdminUsers();
1396 } catch (err) {
1582 } catch (err)
1583 {
1397 1584 document.getElementById('user-error').textContent = err.message;
1398 1585 document.getElementById('user-error').classList.remove('hidden');
1399 1586 }
@@ -1404,31 +1591,33 @@ function openUserModal(user, paths) {
1404 1591 // SVG ICONS
1405 1592 // ───────────────────────────────────────────────────────────────────────────
1406 1593
1407 const IMAGE_EXTS = new Set(['jpg','jpeg','png','gif','webp','svg','bmp','ico','avif']);
1408 const VIDEO_EXTS = new Set(['mp4','webm','ogv','mov','avi','mkv']);
1409 const AUDIO_EXTS = new Set(['mp3','ogg','wav','flac','aac','m4a']);
1410 const DOC_EXTS = new Set(['pdf','doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp']);
1411 const CODE_EXTS = new Set(['js','ts','py','rb','go','rs','c','cpp','h','cs','java','php','html','css','json','xml','yaml','yml','sh','bash','md','txt']);
1412 const ARCHIVE_EXTS= new Set(['zip','tar','gz','bz2','xz','rar','7z']);
1594 const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
1595 const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
1596 const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
1597 const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
1598 const CODE_EXTS = new Set(['js', 'ts', 'py', 'rb', 'go', 'rs', 'c', 'cpp', 'h', 'cs', 'java', 'php', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'txt']);
1599 const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
1413 1600
1414 function iconFolder(size = 52) {
1601 function iconFolder (size = 52)
1602 {
1415 1603 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1416 1604 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
1417 1605 <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
1418 1606 </svg>`;
1419 1607 }
1420 1608
1421 function iconFile(name, size = 52) {
1422 const ext = extOf(name);
1423 let color = '#7880a0';
1424 let symbol = '';
1609 function iconFile (name, size = 52)
1610 {
1611 const ext = extOf(name);
1612 let color = '#7880a0';
1613 let symbol = '';
1425 1614
1426 if (IMAGE_EXTS.has(ext)) color = '#3fcf8e';
1427 else if (VIDEO_EXTS.has(ext)) color = '#e05c6e';
1428 else if (AUDIO_EXTS.has(ext)) color = '#c084fc';
1429 else if (DOC_EXTS.has(ext)) color = '#f97316';
1430 else if (CODE_EXTS.has(ext)) color = '#38bdf8';
1431 else if (ARCHIVE_EXTS.has(ext))color = '#facc15';
1615 if (IMAGE_EXTS.has(ext)) color = '#3fcf8e';
1616 else if (VIDEO_EXTS.has(ext)) color = '#e05c6e';
1617 else if (AUDIO_EXTS.has(ext)) color = '#c084fc';
1618 else if (DOC_EXTS.has(ext)) color = '#f97316';
1619 else if (CODE_EXTS.has(ext)) color = '#38bdf8';
1620 else if (ARCHIVE_EXTS.has(ext)) color = '#facc15';
1432 1621
1433 1622 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1434 1623 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
@@ -1441,22 +1630,25 @@ function iconFile(name, size = 52) {
1441 1630 // EVENT WIRING
1442 1631 // ───────────────────────────────────────────────────────────────────────────
1443 1632
1444 function wireEvents() {
1633 function wireEvents ()
1634 {
1445 1635 // Auth form
1446 document.getElementById('auth-form').addEventListener('submit', async (e) => {
1636 document.getElementById('auth-form').addEventListener('submit', async (e) =>
1637 {
1447 1638 e.preventDefault();
1448 1639 const username = document.getElementById('auth-username').value.trim();
1449 1640 const password = document.getElementById('auth-password').value;
1450 const isSetup = e.target.dataset.mode === 'setup';
1451 const errEl = document.getElementById('auth-error');
1452 const btn = document.getElementById('auth-submit');
1453 btn.disabled = true;
1641 const isSetup = e.target.dataset.mode === 'setup';
1642 const errEl = document.getElementById('auth-error');
1643 const btn = document.getElementById('auth-submit');
1644 btn.disabled = true;
1454 1645 btn.textContent = 'Please wait…';
1455 1646 const err = await doLogin(username, password, isSetup);
1456 if (err) {
1647 if (err)
1648 {
1457 1649 errEl.textContent = err;
1458 1650 errEl.classList.remove('hidden');
1459 btn.disabled = false;
1651 btn.disabled = false;
1460 1652 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
1461 1653 }
1462 1654 });
@@ -1465,51 +1657,60 @@ function wireEvents() {
1465 1657 document.getElementById('btn-logout').addEventListener('click', logout);
1466 1658
1467 1659 // Hard refresh while keeping auth/session state.
1468 document.getElementById('btn-refresh').addEventListener('click', () => {
1660 document.getElementById('btn-refresh').addEventListener('click', () =>
1661 {
1469 1662 saveSessionState();
1470 1663 location.reload();
1471 1664 });
1472 1665
1473 1666 // Upload button
1474 document.getElementById('btn-upload').addEventListener('click', () => {
1667 document.getElementById('btn-upload').addEventListener('click', () =>
1668 {
1475 1669 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1476 if (!canWrite()) { toast('No write access.', 'err'); return; }
1670 if (!canWrite()) { toast('No write access.', 'err'); return; }
1477 1671 document.getElementById('file-input').click();
1478 1672 });
1479 1673
1480 document.getElementById('file-input').addEventListener('change', async (e) => {
1674 document.getElementById('file-input').addEventListener('change', async (e) =>
1675 {
1481 1676 if (e.target.files.length) await uploadFiles(e.target.files);
1482 1677 e.target.value = '';
1483 1678 });
1484 1679
1485 document.getElementById('btn-upload-folder').addEventListener('click', () => {
1680 document.getElementById('btn-upload-folder').addEventListener('click', () =>
1681 {
1486 1682 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1487 if (!canWrite()) { toast('No write access.', 'err'); return; }
1683 if (!canWrite()) { toast('No write access.', 'err'); return; }
1488 1684 document.getElementById('folder-input').click();
1489 1685 });
1490 1686
1491 document.getElementById('folder-input').addEventListener('change', async (e) => {
1687 document.getElementById('folder-input').addEventListener('change', async (e) =>
1688 {
1492 1689 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
1493 1690 e.target.value = '';
1494 1691 });
1495 1692
1496 document.getElementById('btn-new-folder').addEventListener('click', async () => {
1693 document.getElementById('btn-new-folder').addEventListener('click', async () =>
1694 {
1497 1695 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1498 if (!canWrite()) { toast('No write access.', 'err'); return; }
1696 if (!canWrite()) { toast('No write access.', 'err'); return; }
1499 1697
1500 1698 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
1501 1699 if (name == null) return;
1502 1700 const folderName = name.trim();
1503 if (!folderName) {
1701 if (!folderName)
1702 {
1504 1703 toast('Folder name is required.', 'err');
1505 1704 return;
1506 1705 }
1507 1706
1508 try {
1707 try
1708 {
1509 1709 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
1510 1710 toast('Folder created.', 'ok');
1511 1711 await navigateTo(STATE.currentDir, STATE.currentRoot);
1512 } catch (err) {
1712 } catch (err)
1713 {
1513 1714 toast(err.message, 'err');
1514 1715 }
1515 1716 });
@@ -1518,7 +1719,8 @@ function wireEvents() {
1518 1719 document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
1519 1720
1520 1721 // Click outside grid closes sidebar
1521 document.getElementById('main-content').addEventListener('click', (e) => {
1722 document.getElementById('main-content').addEventListener('click', (e) =>
1723 {
1522 1724 if (!e.target.closest('.file-item')) closeSidebar();
1523 1725 });
1524 1726
@@ -1528,7 +1730,8 @@ function wireEvents() {
1528 1730 document.getElementById('admin-modal').classList.add('hidden'));
1529 1731
1530 1732 // Add path
1531 document.getElementById('admin-add-path').addEventListener('click', () => {
1733 document.getElementById('admin-add-path').addEventListener('click', () =>
1734 {
1532 1735 const val = document.getElementById('admin-new-path').value.trim();
1533 1736 if (!val) return;
1534 1737 const row = document.createElement('div');
@@ -1540,10 +1743,12 @@ function wireEvents() {
1540 1743 });
1541 1744
1542 1745 // Save paths
1543 document.getElementById('admin-save-paths').addEventListener('click', async () => {
1544 const rows = document.querySelectorAll('#admin-paths .path-row span');
1746 document.getElementById('admin-save-paths').addEventListener('click', async () =>
1747 {
1748 const rows = document.querySelectorAll('#admin-paths .path-row span');
1545 1749 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
1546 try {
1750 try
1751 {
1547 1752 await api('PUT', '/admin/config', { paths });
1548 1753 toast('Paths saved.', 'ok');
1549 1754 await loadRoots();
@@ -1551,13 +1756,16 @@ function wireEvents() {
1551 1756 });
1552 1757
1553 1758 // Shutdown server
1554 document.getElementById('admin-shutdown-btn').addEventListener('click', async () => {
1759 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
1760 {
1555 1761 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
1556 try {
1762 try
1763 {
1557 1764 await api('POST', '/admin/shutdown');
1558 1765 toast('Server is shutting down…', 'ok');
1559 1766 document.getElementById('admin-modal').classList.add('hidden');
1560 } catch {
1767 } catch
1768 {
1561 1769 // Fetch may throw because the connection closes before a response arrives.
1562 1770 toast('Server is shutting down…', 'ok');
1563 1771 document.getElementById('admin-modal').classList.add('hidden');
@@ -1565,8 +1773,9 @@ function wireEvents() {
1565 1773 });
1566 1774
1567 1775 // New user
1568 document.getElementById('admin-new-user-btn').addEventListener('click', async () => {
1569 const cfg = await api('GET', '/admin/config');
1776 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
1777 {
1778 const cfg = await api('GET', '/admin/config');
1570 1779 const paths = cfg ? (cfg.effectivePaths || []) : [];
1571 1780 openUserModal(null, paths);
1572 1781 });
@@ -1580,8 +1789,10 @@ function wireEvents() {
1580 1789 document.getElementById('rename-modal').classList.add('hidden'));
1581 1790
1582 1791 // Close modals on backdrop click
1583 document.querySelectorAll('.modal-overlay').forEach(overlay => {
1584 overlay.addEventListener('click', e => {
1792 document.querySelectorAll('.modal-overlay').forEach(overlay =>
1793 {
1794 overlay.addEventListener('click', e =>
1795 {
1585 1796 if (e.target === overlay) overlay.classList.add('hidden');
1586 1797 });
1587 1798 });
@@ -1591,7 +1802,8 @@ function wireEvents() {
1591 1802 // BOOT
1592 1803 // ───────────────────────────────────────────────────────────────────────────
1593 1804
1594 (async function boot() {
1805 (async function boot ()
1806 {
1595 1807 wireEvents();
1596 1808 initDragDrop();
1597 1809 window.addEventListener('beforeunload', saveSessionState);
@@ -13,14 +13,14 @@
13// STATE
13// STATE
14// ───────────────────────────────────────────────────────────────────────────
14// ───────────────────────────────────────────────────────────────────────────
15const STATE = {
15const STATE = {
16 token: null, // decrypted JWT string
16 token: null, // decrypted JWT string
17 username: null,
17 username: null,
18 isAdmin: false,
18 isAdmin: false,
19 permissions: {},
19 permissions: {},
20 roots: [], // [{ label, path }]
20 roots: [], // [{ label, path }]
21 currentDir: null, // absolute path currently shown (null = roots view)
21 currentDir: null, // absolute path currently shown (null = roots view)
22 currentRoot: null, // { label, path } of the active root
22 currentRoot: null, // { label, path } of the active root
23 items: [], // current directory listing
23 items: [], // current directory listing
24 selectedItem: null, // item object selected in sidebar
24 selectedItem: null, // item object selected in sidebar
25
25
26 // Ephemeral key pair per session (client-side)
26 // Ephemeral key pair per session (client-side)
@@ -51,14 +51,15 @@ const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
51// CRYPTO HELPERS (Web Crypto API)
51// CRYPTO HELPERS (Web Crypto API)
52// ───────────────────────────────────────────────────────────────────────────
52// ───────────────────────────────────────────────────────────────────────────
53
53
54async function generateClientKeyPair() {
54async function generateClientKeyPair ()
55{
55 if (!hasWebCrypto()) return;
56 if (!hasWebCrypto()) return;
56 const kp = await crypto.subtle.generateKey(
57 const kp = await crypto.subtle.generateKey(
57 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' },
58 { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
58 true,
59 true,
59 ['encrypt', 'decrypt'],
60 ['encrypt', 'decrypt'],
60 );
61 );
61 STATE.clientPrivateKey = kp.privateKey;
62 STATE.clientPrivateKey = kp.privateKey;
62 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
63 STATE.clientPublicKeyJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
63}
64}
64
65
@@ -66,8 +67,10 @@ async function generateClientKeyPair() {
66 * Hybrid-encrypt a JS object using the server's RSA public key.
67 * Hybrid-encrypt a JS object using the server's RSA public key.
67 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
68 * Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
68 */
69 */
69async function hybridEncryptForServer(obj) {
70async function hybridEncryptForServer (obj)
70 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) {
71{
72 if (!hasWebCrypto() || !STATE.serverPublicKeyJwk)
73 {
71 return { plaintext: obj };
74 return { plaintext: obj };
72 }
75 }
73
76
@@ -77,39 +80,40 @@ async function hybridEncryptForServer(obj) {
77 false, ['encrypt'],
80 false, ['encrypt'],
78 );
81 );
79
82
80 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
83 const plaintext = new TextEncoder().encode(JSON.stringify(obj));
81 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
84 const aesKey = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
82 const iv = crypto.getRandomValues(new Uint8Array(12));
85 const iv = crypto.getRandomValues(new Uint8Array(12));
83 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
86 const gcmResult = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aesKey, plaintext);
84
87
85 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
88 // gcmResult = ciphertext || tag (last 16 bytes are auth tag)
86 const gcmBytes = new Uint8Array(gcmResult);
89 const gcmBytes = new Uint8Array(gcmResult);
87 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
90 const ciphertext = gcmBytes.slice(0, gcmBytes.length - 16);
88 const tag = gcmBytes.slice(gcmBytes.length - 16);
91 const tag = gcmBytes.slice(gcmBytes.length - 16);
89
92
90 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
93 const rawAes = await crypto.subtle.exportKey('raw', aesKey);
91 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
94 const encryptedKey = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, serverPub, rawAes);
92
95
93 return {
96 return {
94 encryptedKey: b64(encryptedKey),
97 encryptedKey: b64(encryptedKey),
95 iv: b64(iv),
98 iv: b64(iv),
96 ciphertext: b64(ciphertext),
99 ciphertext: b64(ciphertext),
97 tag: b64(tag),
100 tag: b64(tag),
98 };
101 };
99}
102}
100
103
101/**
104/**
102 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
105 * Hybrid-decrypt a payload encrypted by the server for us (using our public key).
103 */
106 */
104async function hybridDecryptFromServer(payload) {
107async function hybridDecryptFromServer (payload)
108{
105 if (!payload) return null;
109 if (!payload) return null;
106 if (payload.token) return payload.token;
110 if (payload.token) return payload.token;
107 if (!hasWebCrypto()) return null;
111 if (!hasWebCrypto()) return null;
108
112
109 const encryptedKey = unb64(payload.encryptedKey);
113 const encryptedKey = unb64(payload.encryptedKey);
110 const iv = unb64(payload.iv);
114 const iv = unb64(payload.iv);
111 const ciphertext = unb64(payload.ciphertext);
115 const ciphertext = unb64(payload.ciphertext);
112 const tag = unb64(payload.tag);
116 const tag = unb64(payload.tag);
113
117
114 const rawAes = await crypto.subtle.decrypt(
118 const rawAes = await crypto.subtle.decrypt(
115 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
119 { name: 'RSA-OAEP' }, STATE.clientPrivateKey, encryptedKey,
@@ -130,23 +134,27 @@ async function hybridDecryptFromServer(payload) {
130// UTIL
134// UTIL
131// ───────────────────────────────────────────────────────────────────────────
135// ───────────────────────────────────────────────────────────────────────────
132
136
133function b64(buf) {
137function b64 (buf)
138{
134 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
139 return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
135}
140}
136
141
137function hasWebCrypto() {
142function hasWebCrypto ()
143{
138 return !!(window.crypto && window.crypto.subtle);
144 return !!(window.crypto && window.crypto.subtle);
139}
145}
140
146
141function unb64(str) {
147function unb64 (str)
148{
142 const binary = atob(str);
149 const binary = atob(str);
143 const buf = new Uint8Array(binary.length);
150 const buf = new Uint8Array(binary.length);
144 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
151 for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
145 return buf.buffer;
152 return buf.buffer;
146}
153}
147
154
148/** Stable browser fingerprint (not stored, derived fresh each load) */
155/** Stable browser fingerprint (not stored, derived fresh each load) */
149function getFingerprint() {
156function getFingerprint ()
157{
150 const binding = getOrCreateClientBindingId();
158 const binding = getOrCreateClientBindingId();
151 const nav = navigator;
159 const nav = navigator;
152
160
@@ -161,35 +169,44 @@ function getFingerprint() {
161 ].join('|');
169 ].join('|');
162}
170}
163
171
164function randomIdHex(bytes = 16) {
172function randomIdHex (bytes = 16)
173{
165 const arr = new Uint8Array(bytes);
174 const arr = new Uint8Array(bytes);
166 if (window.crypto && typeof window.crypto.getRandomValues === 'function') {
175 if (window.crypto && typeof window.crypto.getRandomValues === 'function')
176 {
167 window.crypto.getRandomValues(arr);
177 window.crypto.getRandomValues(arr);
168 } else {
178 } else
179 {
169 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
180 for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
170 }
181 }
171 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
182 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
172}
183}
173
184
174function getOrCreateClientBindingId() {
185function getOrCreateClientBindingId ()
186{
175 if (STATE.clientBindingId) return STATE.clientBindingId;
187 if (STATE.clientBindingId) return STATE.clientBindingId;
176
188
177 try {
189 try
190 {
178 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
191 const existing = localStorage.getItem(CLIENT_BINDING_KEY);
179 if (existing && typeof existing === 'string') {
192 if (existing && typeof existing === 'string')
193 {
180 STATE.clientBindingId = existing;
194 STATE.clientBindingId = existing;
181 return existing;
195 return existing;
182 }
196 }
183 } catch {
197 } catch
198 {
184 // Ignore storage read errors.
199 // Ignore storage read errors.
185 }
200 }
186
201
187 const created = randomIdHex(16);
202 const created = randomIdHex(16);
188 STATE.clientBindingId = created;
203 STATE.clientBindingId = created;
189
204
190 try {
205 try
206 {
191 localStorage.setItem(CLIENT_BINDING_KEY, created);
207 localStorage.setItem(CLIENT_BINDING_KEY, created);
192 } catch {
208 } catch
209 {
193 // Ignore storage write errors; in-memory fallback still keeps this stable
210 // Ignore storage write errors; in-memory fallback still keeps this stable
194 // for the current page session.
211 // for the current page session.
195 }
212 }
@@ -197,42 +214,49 @@ function getOrCreateClientBindingId() {
197 return created;
214 return created;
198}
215}
199
216
200function formatBytes(bytes) {
217function formatBytes (bytes)
218{
201 if (bytes == null) return '—';
219 if (bytes == null) return '—';
202 if (bytes < 1024) return bytes + ' B';
220 if (bytes < 1024) return bytes + ' B';
203 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
221 if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
204 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
222 if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
205 return (bytes / 1073741824).toFixed(2) + ' GB';
223 return (bytes / 1073741824).toFixed(2) + ' GB';
206}
224}
207
225
208function extOf(name) {
226function extOf (name)
227{
209 const i = name.lastIndexOf('.');
228 const i = name.lastIndexOf('.');
210 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
229 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
211}
230}
212
231
213function getPathSep(basePath) {
232function getPathSep (basePath)
233{
214 return basePath && basePath.includes('\\') ? '\\' : '/';
234 return basePath && basePath.includes('\\') ? '\\' : '/';
215}
235}
216
236
217function joinServerPath(basePath, segment) {
237function joinServerPath (basePath, segment)
238{
218 const sep = getPathSep(basePath);
239 const sep = getPathSep(basePath);
219 const base = String(basePath || '').replace(/[\\/]+$/, '');
240 const base = String(basePath || '').replace(/[\\/]+$/, '');
220 return base + sep + segment;
241 return base + sep + segment;
221}
242}
222
243
223function samePath(a, b) {
244function samePath (a, b)
245{
224 if (!a || !b) return false;
246 if (!a || !b) return false;
225 return String(a).toLowerCase() === String(b).toLowerCase();
247 return String(a).toLowerCase() === String(b).toLowerCase();
226}
248}
227
249
228function pathInside(child, root) {
250function pathInside (child, root)
251{
229 if (!child || !root) return false;
252 if (!child || !root) return false;
230 if (samePath(child, root)) return true;
253 if (samePath(child, root)) return true;
231 const sep = getPathSep(root);
254 const sep = getPathSep(root);
232 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
255 return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
233}
256}
234
257
235function saveSessionState() {
258function saveSessionState ()
259{
236 if (!STATE.token) return;
260 if (!STATE.token) return;
237 const now = Date.now();
261 const now = Date.now();
238 STATE.lastOperationAt = now;
262 STATE.lastOperationAt = now;
@@ -242,33 +266,40 @@ function saveSessionState() {
242 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
266 rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
243 lastOperationAt: STATE.lastOperationAt,
267 lastOperationAt: STATE.lastOperationAt,
244 };
268 };
245 try {
269 try
270 {
246 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
271 localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
247 } catch {
272 } catch
273 {
248 // Ignore storage errors (private mode/full quota).
274 // Ignore storage errors (private mode/full quota).
249 }
275 }
250}
276}
251
277
252function loadSessionState() {
278function loadSessionState ()
253 try {
279{
280 try
281 {
254 const raw = localStorage.getItem(SESSION_KEY);
282 const raw = localStorage.getItem(SESSION_KEY);
255 if (!raw) return null;
283 if (!raw) return null;
256 const parsed = JSON.parse(raw);
284 const parsed = JSON.parse(raw);
257 if (!parsed || typeof parsed.token !== 'string') return null;
285 if (!parsed || typeof parsed.token !== 'string') return null;
258 if (!Number.isFinite(parsed.lastOperationAt)) return null;
286 if (!Number.isFinite(parsed.lastOperationAt)) return null;
259
287
260 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) {
288 if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS)
289 {
261 clearSessionState();
290 clearSessionState();
262 return null;
291 return null;
263 }
292 }
264
293
265 return parsed;
294 return parsed;
266 } catch {
295 } catch
296 {
267 return null;
297 return null;
268 }
298 }
269}
299}
270
300
271function clearSessionState() {
301function clearSessionState ()
302{
272 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
303 try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
273}
304}
274
305
@@ -276,12 +307,14 @@ function clearSessionState() {
276// API
307// API
277// ───────────────────────────────────────────────────────────────────────────
308// ───────────────────────────────────────────────────────────────────────────
278
309
279async function api(method, path, body, opts = {}) {
310async function api (method, path, body, opts = {})
311{
280 const headers = { 'Content-Type': 'application/json' };
312 const headers = { 'Content-Type': 'application/json' };
281 const noAutoLogout = !!opts.noAutoLogout;
313 const noAutoLogout = !!opts.noAutoLogout;
282 if (STATE.token) {
314 if (STATE.token)
315 {
283 headers['Authorization'] = 'Bearer ' + STATE.token;
316 headers['Authorization'] = 'Bearer ' + STATE.token;
284 headers['X-Fp'] = getFingerprint();
317 headers['X-Fp'] = getFingerprint();
285 }
318 }
286 const fetchOpts = { ...opts };
319 const fetchOpts = { ...opts };
287 delete fetchOpts.noAutoLogout;
320 delete fetchOpts.noAutoLogout;
@@ -291,16 +324,19 @@ async function api(method, path, body, opts = {}) {
291 body: body != null ? JSON.stringify(body) : undefined,
324 body: body != null ? JSON.stringify(body) : undefined,
292 ...fetchOpts,
325 ...fetchOpts,
293 });
326 });
294 if (!res.ok) {
327 if (!res.ok)
328 {
295 const j = await res.json().catch(() => ({}));
329 const j = await res.json().catch(() => ({}));
296 // Session-expired → force re-login
330 // Session-expired → force re-login
297 if (res.status === 401) {
331 if (res.status === 401)
332 {
298 if (!noAutoLogout) logout();
333 if (!noAutoLogout) logout();
299 return null;
334 return null;
300 }
335 }
301 throw new Error(j.error || res.statusText);
336 throw new Error(j.error || res.statusText);
302 }
337 }
303 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) {
338 if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed'))
339 {
304 saveSessionState();
340 saveSessionState();
305 }
341 }
306 return res.json();
342 return res.json();
@@ -310,7 +346,8 @@ async function api(method, path, body, opts = {}) {
310// TOAST
346// TOAST
311// ───────────────────────────────────────────────────────────────────────────
347// ───────────────────────────────────────────────────────────────────────────
312
348
313function toast(msg, type = '') {
349function toast (msg, type = '')
350{
314 const el = document.createElement('div');
351 const el = document.createElement('div');
315 el.className = 'toast-msg' + (type ? ' ' + type : '');
352 el.className = 'toast-msg' + (type ? ' ' + type : '');
316 el.textContent = msg;
353 el.textContent = msg;
@@ -328,24 +365,27 @@ function toast(msg, type = '') {
328 * @param {string} message
365 * @param {string} message
329 * @returns {Promise<boolean>} true = OK, false = Cancel
366 * @returns {Promise<boolean>} true = OK, false = Cancel
330 */
367 */
331function showConfirm(title, message) {
368function showConfirm (title, message)
332 return new Promise((resolve) => {
369{
370 return new Promise((resolve) =>
371 {
333 const overlay = document.getElementById('confirm-modal');
372 const overlay = document.getElementById('confirm-modal');
334 document.getElementById('confirm-modal-title').textContent = title;
373 document.getElementById('confirm-modal-title').textContent = title;
335 document.getElementById('confirm-modal-message').textContent = message;
374 document.getElementById('confirm-modal-message').textContent = message;
336 overlay.classList.remove('hidden');
375 overlay.classList.remove('hidden');
337
376
338 const ok = document.getElementById('confirm-modal-ok');
377 const ok = document.getElementById('confirm-modal-ok');
339 const cancel = document.getElementById('confirm-modal-cancel');
378 const cancel = document.getElementById('confirm-modal-cancel');
340
379
341 function finish(result) {
380 function finish (result)
381 {
342 overlay.classList.add('hidden');
382 overlay.classList.add('hidden');
343 ok.removeEventListener('click', onOk);
383 ok.removeEventListener('click', onOk);
344 cancel.removeEventListener('click', onCancel);
384 cancel.removeEventListener('click', onCancel);
345 resolve(result);
385 resolve(result);
346 }
386 }
347 function onOk() { finish(true); }
387 function onOk () { finish(true); }
348 function onCancel() { finish(false); }
388 function onCancel () { finish(false); }
349
389
350 ok.addEventListener('click', onOk);
390 ok.addEventListener('click', onOk);
351 cancel.addEventListener('click', onCancel);
391 cancel.addEventListener('click', onCancel);
@@ -360,14 +400,16 @@ function showConfirm(title, message) {
360 * @param {string} [defaultValue] — pre-filled value
400 * @param {string} [defaultValue] — pre-filled value
361 * @returns {Promise<string|null>} string = submitted value, null = cancelled
401 * @returns {Promise<string|null>} string = submitted value, null = cancelled
362 */
402 */
363function showPrompt(title, message = '', defaultValue = '') {
403function showPrompt (title, message = '', defaultValue = '')
364 return new Promise((resolve) => {
404{
405 return new Promise((resolve) =>
406 {
365 const overlay = document.getElementById('prompt-modal');
407 const overlay = document.getElementById('prompt-modal');
366 const msgEl = document.getElementById('prompt-modal-message');
408 const msgEl = document.getElementById('prompt-modal-message');
367 const input = document.getElementById('prompt-modal-input');
409 const input = document.getElementById('prompt-modal-input');
368 const errorEl = document.getElementById('prompt-modal-error');
410 const errorEl = document.getElementById('prompt-modal-error');
369 const form = document.getElementById('prompt-modal-form');
411 const form = document.getElementById('prompt-modal-form');
370 const cancel = document.getElementById('prompt-modal-cancel');
412 const cancel = document.getElementById('prompt-modal-cancel');
371
413
372 document.getElementById('prompt-modal-title').textContent = title;
414 document.getElementById('prompt-modal-title').textContent = title;
373 msgEl.textContent = message;
415 msgEl.textContent = message;
@@ -378,17 +420,19 @@ function showPrompt(title, message = '', defaultValue = '') {
378 input.focus();
420 input.focus();
379 input.select();
421 input.select();
380
422
381 function finish(result) {
423 function finish (result)
424 {
382 overlay.classList.add('hidden');
425 overlay.classList.add('hidden');
383 form.removeEventListener('submit', onSubmit);
426 form.removeEventListener('submit', onSubmit);
384 cancel.removeEventListener('click', onCancel);
427 cancel.removeEventListener('click', onCancel);
385 resolve(result);
428 resolve(result);
386 }
429 }
387 function onSubmit(e) {
430 function onSubmit (e)
431 {
388 e.preventDefault();
432 e.preventDefault();
389 finish(input.value);
433 finish(input.value);
390 }
434 }
391 function onCancel() { finish(null); }
435 function onCancel () { finish(null); }
392
436
393 form.addEventListener('submit', onSubmit);
437 form.addEventListener('submit', onSubmit);
394 cancel.addEventListener('click', onCancel);
438 cancel.addEventListener('click', onCancel);
@@ -400,18 +444,21 @@ function showPrompt(title, message = '', defaultValue = '') {
400 * @param {string} filename
444 * @param {string} filename
401 * @returns {Promise<'yes'|'no'|'all'|'none'>}
445 * @returns {Promise<'yes'|'no'|'all'|'none'>}
402 */
446 */
403function showOverwrite(filename) {
447function showOverwrite (filename)
404 return new Promise((resolve) => {
448{
449 return new Promise((resolve) =>
450 {
405 const overlay = document.getElementById('overwrite-modal');
451 const overlay = document.getElementById('overwrite-modal');
406 document.getElementById('overwrite-modal-filename').textContent = filename;
452 document.getElementById('overwrite-modal-filename').textContent = filename;
407 overlay.classList.remove('hidden');
453 overlay.classList.remove('hidden');
408
454
409 const btnYes = document.getElementById('overwrite-modal-yes');
455 const btnYes = document.getElementById('overwrite-modal-yes');
410 const btnNo = document.getElementById('overwrite-modal-no');
456 const btnNo = document.getElementById('overwrite-modal-no');
411 const btnAll = document.getElementById('overwrite-modal-all');
457 const btnAll = document.getElementById('overwrite-modal-all');
412 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
458 const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
413
459
414 function finish(result) {
460 function finish (result)
461 {
415 overlay.classList.add('hidden');
462 overlay.classList.add('hidden');
416 btnYes.removeEventListener('click', onYes);
463 btnYes.removeEventListener('click', onYes);
417 btnNo.removeEventListener('click', onNo);
464 btnNo.removeEventListener('click', onNo);
@@ -419,10 +466,10 @@ function showOverwrite(filename) {
419 btnSkipAll.removeEventListener('click', onSkipAll);
466 btnSkipAll.removeEventListener('click', onSkipAll);
420 resolve(result);
467 resolve(result);
421 }
468 }
422 function onYes() { finish('yes'); }
469 function onYes () { finish('yes'); }
423 function onNo() { finish('no'); }
470 function onNo () { finish('no'); }
424 function onAll() { finish('all'); }
471 function onAll () { finish('all'); }
425 function onSkipAll() { finish('none'); }
472 function onSkipAll () { finish('none'); }
426
473
427 btnYes.addEventListener('click', onYes);
474 btnYes.addEventListener('click', onYes);
428 btnNo.addEventListener('click', onNo);
475 btnNo.addEventListener('click', onNo);
@@ -436,7 +483,8 @@ function showOverwrite(filename) {
436// AUTH FLOW
483// AUTH FLOW
437// ───────────────────────────────────────────────────────────────────────────
484// ───────────────────────────────────────────────────────────────────────────
438
485
439function showAuthOverlay(setupMode = false) {
486function showAuthOverlay (setupMode = false)
487{
440 document.getElementById('app').classList.add('hidden');
488 document.getElementById('app').classList.add('hidden');
441 const overlay = document.getElementById('auth-overlay');
489 const overlay = document.getElementById('auth-overlay');
442 overlay.classList.remove('hidden');
490 overlay.classList.remove('hidden');
@@ -452,16 +500,19 @@ function showAuthOverlay(setupMode = false) {
452 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
500 document.getElementById('auth-form').dataset.mode = setupMode ? 'setup' : 'login';
453}
501}
454
502
455function showApp() {
503function showApp ()
504{
456 document.getElementById('auth-overlay').classList.add('hidden');
505 document.getElementById('auth-overlay').classList.add('hidden');
457 document.getElementById('app').classList.remove('hidden');
506 document.getElementById('app').classList.remove('hidden');
458 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
507 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
459 startAutoRefresh();
508 startAutoRefresh();
460}
509}
461
510
462async function initAuth() {
511async function initAuth ()
512{
463 // Always generate a fresh key pair so each page-load session is independent
513 // Always generate a fresh key pair so each page-load session is independent
464 await generateClientKeyPair().catch(() => {
514 await generateClientKeyPair().catch(() =>
515 {
465 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
516 toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
466 });
517 });
467
518
@@ -474,16 +525,19 @@ async function initAuth() {
474 // Check whether first-run setup is needed
525 // Check whether first-run setup is needed
475 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
526 const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
476
527
477 if (!needed) {
528 if (!needed)
529 {
478 const saved = loadSessionState();
530 const saved = loadSessionState();
479 if (saved && saved.token) {
531 if (saved && saved.token)
532 {
480 STATE.token = saved.token;
533 STATE.token = saved.token;
481 STATE.restoreDir = saved.dir || null;
534 STATE.restoreDir = saved.dir || null;
482 STATE.restoreRootPath = saved.rootPath || null;
535 STATE.restoreRootPath = saved.rootPath || null;
483 STATE.lastOperationAt = saved.lastOperationAt;
536 STATE.lastOperationAt = saved.lastOperationAt;
484
537
485 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
538 const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
486 if (me) {
539 if (me)
540 {
487 STATE.username = me.username;
541 STATE.username = me.username;
488 STATE.isAdmin = me.isAdmin;
542 STATE.isAdmin = me.isAdmin;
489 STATE.permissions = me.permissions;
543 STATE.permissions = me.permissions;
@@ -503,18 +557,21 @@ async function initAuth() {
503 showAuthOverlay(needed);
557 showAuthOverlay(needed);
504}
558}
505
559
506async function doLogin(username, password, isSetup) {
560async function doLogin (username, password, isSetup)
561{
507 const encrypted = await hybridEncryptForServer({ username, password });
562 const encrypted = await hybridEncryptForServer({ username, password });
508 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
563 const endpoint = isSetup ? '/auth/setup' : '/auth/login';
509
564
510 let data;
565 let data;
511 try {
566 try
567 {
512 data = await api('POST', endpoint, {
568 data = await api('POST', endpoint, {
513 encrypted,
569 encrypted,
514 clientPublicKey: STATE.clientPublicKeyJwk,
570 clientPublicKey: STATE.clientPublicKeyJwk,
515 fingerprint: getFingerprint(),
571 fingerprint: getFingerprint(),
516 });
572 });
517 } catch (err) {
573 } catch (err)
574 {
518 return err.message;
575 return err.message;
519 }
576 }
520
577
@@ -529,8 +586,8 @@ async function doLogin(username, password, isSetup) {
529 const me = await api('GET', '/auth/me');
586 const me = await api('GET', '/auth/me');
530 if (!me) return 'Session error.';
587 if (!me) return 'Session error.';
531
588
532 STATE.username = me.username;
589 STATE.username = me.username;
533 STATE.isAdmin = me.isAdmin;
590 STATE.isAdmin = me.isAdmin;
534 STATE.permissions = me.permissions;
591 STATE.permissions = me.permissions;
535
592
536 saveSessionState();
593 saveSessionState();
@@ -539,29 +596,34 @@ async function doLogin(username, password, isSetup) {
539 return null; // no error
596 return null; // no error
540}
597}
541
598
542function logout() {
599function logout ()
600{
543 void performLogout();
601 void performLogout();
544}
602}
545
603
546async function performLogout() {
604async function performLogout ()
605{
547 const tokenAtStart = STATE.token;
606 const tokenAtStart = STATE.token;
548 stopAutoRefresh();
607 stopAutoRefresh();
549
608
550 if (tokenAtStart) {
609 if (tokenAtStart)
551 try {
610 {
611 try
612 {
552 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
613 await api('POST', '/auth/logout', {}, { noAutoLogout: true });
553 } catch {
614 } catch
615 {
554 // Ignore network errors while logging out locally.
616 // Ignore network errors while logging out locally.
555 }
617 }
556 }
618 }
557
619
558 STATE.token = null;
620 STATE.token = null;
559 STATE.username = null;
621 STATE.username = null;
560 STATE.isAdmin = false;
622 STATE.isAdmin = false;
561 STATE.permissions = {};
623 STATE.permissions = {};
562 STATE.currentDir = null;
624 STATE.currentDir = null;
563 STATE.currentRoot = null;
625 STATE.currentRoot = null;
564 STATE.items = [];
626 STATE.items = [];
565 STATE.restoreDir = null;
627 STATE.restoreDir = null;
566 STATE.restoreRootPath = null;
628 STATE.restoreRootPath = null;
567 STATE.lastOperationAt = null;
629 STATE.lastOperationAt = null;
@@ -574,7 +636,8 @@ async function performLogout() {
574// NAVIGATION
636// NAVIGATION
575// ───────────────────────────────────────────────────────────────────────────
637// ───────────────────────────────────────────────────────────────────────────
576
638
577async function loadRoots(opts = {}) {
639async function loadRoots (opts = {})
640{
578 const data = await api('GET', '/files/roots');
641 const data = await api('GET', '/files/roots');
579 if (!data) return;
642 if (!data) return;
580 STATE.roots = data.roots;
643 STATE.roots = data.roots;
@@ -582,28 +645,35 @@ async function loadRoots(opts = {}) {
582 const preferredDir = opts.preferredDir || null;
645 const preferredDir = opts.preferredDir || null;
583 const preferredRootPath = opts.preferredRootPath || null;
646 const preferredRootPath = opts.preferredRootPath || null;
584
647
585 if (preferredDir && preferredRootPath) {
648 if (preferredDir && preferredRootPath)
649 {
586 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
650 const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
587 if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) {
651 if (preferredRoot && pathInside(preferredDir, preferredRoot.path))
588 try {
652 {
653 try
654 {
589 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
655 await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
590 return;
656 return;
591 } catch {
657 } catch
658 {
592 // Fall back to default root behavior.
659 // Fall back to default root behavior.
593 }
660 }
594 }
661 }
595 }
662 }
596
663
597 if (STATE.roots.length === 1) {
664 if (STATE.roots.length === 1)
665 {
598 // Single root → open it directly
666 // Single root → open it directly
599 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
667 await navigateTo(STATE.roots[0].path, STATE.roots[0]);
600 } else {
668 } else
669 {
601 renderRootsView();
670 renderRootsView();
602 }
671 }
603}
672}
604
673
605function renderRootsView() {
674function renderRootsView ()
606 STATE.currentDir = null;
675{
676 STATE.currentDir = null;
607 STATE.currentRoot = null;
677 STATE.currentRoot = null;
608 saveSessionState();
678 saveSessionState();
609 renderBreadcrumb();
679 renderBreadcrumb();
@@ -613,13 +683,15 @@ function renderRootsView() {
613 document.getElementById('folder-stats').classList.add('hidden');
683 document.getElementById('folder-stats').classList.add('hidden');
614 closeSidebar();
684 closeSidebar();
615
685
616 for (const root of STATE.roots) {
686 for (const root of STATE.roots)
687 {
617 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
688 const el = makeFileItem({ name: root.label, isDir: true, path: root.path, _root: root });
618 grid.appendChild(el);
689 grid.appendChild(el);
619 }
690 }
620}
691}
621
692
622async function navigateTo(absPath, root, opts = {}) {
693async function navigateTo (absPath, root, opts = {})
694{
623 if (root) STATE.currentRoot = root;
695 if (root) STATE.currentRoot = root;
624 STATE.currentDir = absPath;
696 STATE.currentDir = absPath;
625
697
@@ -634,7 +706,8 @@ async function navigateTo(absPath, root, opts = {}) {
634 if (!opts.keepSidebar) closeSidebar();
706 if (!opts.keepSidebar) closeSidebar();
635}
707}
636
708
637function renderBreadcrumb() {
709function renderBreadcrumb ()
710{
638 const nav = document.getElementById('breadcrumb');
711 const nav = document.getElementById('breadcrumb');
639 nav.innerHTML = '';
712 nav.innerHTML = '';
640
713
@@ -642,10 +715,13 @@ function renderBreadcrumb() {
642 const home = document.createElement('span');
715 const home = document.createElement('span');
643 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
716 home.className = 'crumb' + (STATE.currentDir == null ? ' active' : '');
644 home.textContent = 'Home';
717 home.textContent = 'Home';
645 home.addEventListener('click', () => {
718 home.addEventListener('click', () =>
646 if (STATE.roots.length === 1) {
719 {
720 if (STATE.roots.length === 1)
721 {
647 navigateTo(STATE.roots[0].path, STATE.roots[0]);
722 navigateTo(STATE.roots[0].path, STATE.roots[0]);
648 } else {
723 } else
724 {
649 renderRootsView();
725 renderRootsView();
650 }
726 }
651 });
727 });
@@ -654,15 +730,16 @@ function renderBreadcrumb() {
654 if (!STATE.currentDir || !STATE.currentRoot) return;
730 if (!STATE.currentDir || !STATE.currentRoot) return;
655
731
656 // Build path segments relative to the root
732 // Build path segments relative to the root
657 const rootPath = STATE.currentRoot.path;
733 const rootPath = STATE.currentRoot.path;
658 const relative = STATE.currentDir === rootPath
734 const relative = STATE.currentDir === rootPath
659 ? ''
735 ? ''
660 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
736 : STATE.currentDir.replace(rootPath, '').replace(/^[\\/]/, '');
661
737
662 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
738 const parts = [STATE.currentRoot.label, ...relative.split(/[\\/]/).filter(Boolean)];
663 let accumulated = rootPath;
739 let accumulated = rootPath;
664
740
665 for (let i = 0; i < parts.length; i++) {
741 for (let i = 0; i < parts.length; i++)
742 {
666 const sep = document.createElement('span');
743 const sep = document.createElement('span');
667 sep.className = 'sep';
744 sep.className = 'sep';
668 sep.textContent = ' / ';
745 sep.textContent = ' / ';
@@ -674,7 +751,8 @@ function renderBreadcrumb() {
674
751
675 // Capture the path for this crumb
752 // Capture the path for this crumb
676 const capturedPath = i === 0 ? rootPath : accumulated;
753 const capturedPath = i === 0 ? rootPath : accumulated;
677 if (i < parts.length - 1) {
754 if (i < parts.length - 1)
755 {
678 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
756 crumb.addEventListener('click', () => navigateTo(capturedPath, STATE.currentRoot));
679 }
757 }
680
758
@@ -682,58 +760,68 @@ function renderBreadcrumb() {
682
760
683 // Advance accumulated path (skip for root label)
761 // Advance accumulated path (skip for root label)
684 if (i > 0) accumulated = accumulated + '/' + parts[i];
762 if (i > 0) accumulated = accumulated + '/' + parts[i];
685 else if (i === 0 && parts.length > 1) {
763 else if (i === 0 && parts.length > 1)
764 {
686 // After root label, next crumb should append the next segment
765 // After root label, next crumb should append the next segment
687 accumulated = rootPath;
766 accumulated = rootPath;
688 }
767 }
689 }
768 }
690}
769}
691
770
692async function refreshFolderStats() {
771async function refreshFolderStats ()
772{
693 const el = document.getElementById('folder-stats');
773 const el = document.getElementById('folder-stats');
694 if (!STATE.currentDir) {
774 if (!STATE.currentDir)
775 {
695 el.classList.add('hidden');
776 el.classList.add('hidden');
696 return;
777 return;
697 }
778 }
698
779
699 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
780 const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
700 if (!data) {
781 if (!data)
782 {
701 el.classList.add('hidden');
783 el.classList.add('hidden');
702 return;
784 return;
703 }
785 }
704
786
705 const used = formatBytes(data.usedBytes);
787 const used = formatBytes(data.usedBytes);
706 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
788 const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
707 el.textContent = `Folder usage (recursive): ${used} | Free on root: ${free}`;
789 el.textContent = `Folder usage: ${used} | Free on disk: ${free}`;
708 el.classList.remove('hidden');
790 el.classList.remove('hidden');
709}
791}
710
792
711function itemsSignature(items) {
793function itemsSignature (items)
794{
712 return JSON.stringify(
795 return JSON.stringify(
713 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
796 (items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
714 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
797 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
715 );
798 );
716}
799}
717
800
718async function incrementalRefreshCurrentDir() {
801async function incrementalRefreshCurrentDir ()
802{
719 if (!STATE.currentDir || STATE.uploadInProgress) return;
803 if (!STATE.currentDir || STATE.uploadInProgress) return;
720 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
804 const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
721 if (!data) return;
805 if (!data) return;
722
806
723 const oldSig = itemsSignature(STATE.items);
807 const oldSig = itemsSignature(STATE.items);
724 const newSig = itemsSignature(data.items);
808 const newSig = itemsSignature(data.items);
725 if (oldSig !== newSig) {
809 if (oldSig !== newSig)
810 {
726 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
811 const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
727 STATE.items = data.items;
812 STATE.items = data.items;
728 renderFileGrid();
813 renderFileGrid();
729
814
730 if (selectedPath) {
815 if (selectedPath)
816 {
731 const match = STATE.items.find(i => i.path === selectedPath);
817 const match = STATE.items.find(i => i.path === selectedPath);
732 if (match) {
818 if (match)
819 {
733 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
820 const selectedEl = Array.from(document.querySelectorAll('.file-item'))
734 .find(el => el.dataset.path === selectedPath);
821 .find(el => el.dataset.path === selectedPath);
735 if (selectedEl) selectItem(selectedEl, match);
822 if (selectedEl) selectItem(selectedEl, match);
736 } else {
823 } else
824 {
737 closeSidebar();
825 closeSidebar();
738 }
826 }
739 }
827 }
@@ -742,16 +830,20 @@ async function incrementalRefreshCurrentDir() {
742 await refreshFolderStats();
830 await refreshFolderStats();
743}
831}
744
832
745function startAutoRefresh() {
833function startAutoRefresh ()
834{
746 stopAutoRefresh();
835 stopAutoRefresh();
747 STATE.autoRefreshTimer = setInterval(() => {
836 STATE.autoRefreshTimer = setInterval(() =>
837 {
748 if (document.hidden) return;
838 if (document.hidden) return;
749 incrementalRefreshCurrentDir();
839 incrementalRefreshCurrentDir();
750 }, 5000);
840 }, 5000);
751}
841}
752
842
753function stopAutoRefresh() {
843function stopAutoRefresh ()
754 if (STATE.autoRefreshTimer) {
844{
845 if (STATE.autoRefreshTimer)
846 {
755 clearInterval(STATE.autoRefreshTimer);
847 clearInterval(STATE.autoRefreshTimer);
756 STATE.autoRefreshTimer = null;
848 STATE.autoRefreshTimer = null;
757 }
849 }
@@ -761,42 +853,48 @@ function stopAutoRefresh() {
761// FILE GRID RENDERING
853// FILE GRID RENDERING
762// ───────────────────────────────────────────────────────────────────────────
854// ───────────────────────────────────────────────────────────────────────────
763
855
764function renderFileGrid() {
856function renderFileGrid ()
857{
765 const grid = document.getElementById('file-grid');
858 const grid = document.getElementById('file-grid');
766 grid.innerHTML = '';
859 grid.innerHTML = '';
767 const empty = document.getElementById('empty-notice');
860 const empty = document.getElementById('empty-notice');
768
861
769 const sorted = [...STATE.items].sort((a, b) => {
862 const sorted = [...STATE.items].sort((a, b) =>
863 {
770 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
864 if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
771 return a.name.localeCompare(b.name);
865 return a.name.localeCompare(b.name);
772 });
866 });
773
867
774 empty.classList.toggle('hidden', sorted.length > 0);
868 empty.classList.toggle('hidden', sorted.length > 0);
775
869
776 for (const item of sorted) {
870 for (const item of sorted)
871 {
777 grid.appendChild(makeFileItem(item));
872 grid.appendChild(makeFileItem(item));
778 }
873 }
779}
874}
780
875
781function makeFileItem(item) {
876function makeFileItem (item)
877{
782 const el = document.createElement('div');
878 const el = document.createElement('div');
783 el.className = 'file-item';
879 el.className = 'file-item';
784 el.dataset.path = item.path;
880 el.dataset.path = item.path;
785
881
786 const icon = document.createElement('div');
882 const icon = document.createElement('div');
787 icon.className = 'icon';
883 icon.className = 'icon';
788 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
884 icon.innerHTML = item.isDir ? iconFolder() : iconFile(item.name);
789 el.appendChild(icon);
885 el.appendChild(icon);
790
886
791 const name = document.createElement('div');
887 const name = document.createElement('div');
792 name.className = 'name';
888 name.className = 'name';
793 name.textContent = item.name;
889 name.textContent = item.name;
794 el.appendChild(name);
890 el.appendChild(name);
795
891
796 // Single-click: open sidebar
892 // Single-click: open sidebar
797 el.addEventListener('click', (e) => {
893 el.addEventListener('click', (e) =>
894 {
798 e.stopPropagation();
895 e.stopPropagation();
799 if (item._root) {
896 if (item._root)
897 {
800 // Clicking a root tile goes straight in
898 // Clicking a root tile goes straight in
801 navigateTo(item.path, item._root);
899 navigateTo(item.path, item._root);
802 return;
900 return;
@@ -805,11 +903,14 @@ function makeFileItem(item) {
805 });
903 });
806
904
807 // Double-click: enter folder or view/download file
905 // Double-click: enter folder or view/download file
808 el.addEventListener('dblclick', (e) => {
906 el.addEventListener('dblclick', (e) =>
907 {
809 e.stopPropagation();
908 e.stopPropagation();
810 if (item.isDir) {
909 if (item.isDir)
910 {
811 navigateTo(item.path, STATE.currentRoot);
911 navigateTo(item.path, STATE.currentRoot);
812 } else {
912 } else
913 {
813 downloadOrView(item);
914 downloadOrView(item);
814 }
915 }
815 });
916 });
@@ -817,7 +918,8 @@ function makeFileItem(item) {
817 return el;
918 return el;
818}
919}
819
920
820function selectItem(el, item) {
921function selectItem (el, item)
922{
821 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
923 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
822 el.classList.add('selected');
924 el.classList.add('selected');
823 STATE.selectedItem = item;
925 STATE.selectedItem = item;
@@ -828,7 +930,8 @@ function selectItem(el, item) {
828// SIDEBAR
930// SIDEBAR
829// ───────────────────────────────────────────────────────────────────────────
931// ───────────────────────────────────────────────────────────────────────────
830
932
831async function openSidebar(item) {
933async function openSidebar (item)
934{
832 const sidebar = document.getElementById('sidebar');
935 const sidebar = document.getElementById('sidebar');
833 sidebar.classList.remove('hidden');
936 sidebar.classList.remove('hidden');
834 document.getElementById('app').classList.add('sidebar-open');
937 document.getElementById('app').classList.add('sidebar-open');
@@ -843,9 +946,11 @@ async function openSidebar(item) {
843 const actions = document.getElementById('sidebar-actions');
946 const actions = document.getElementById('sidebar-actions');
844 actions.innerHTML = '';
947 actions.innerHTML = '';
845
948
846 if (!item.isDir) {
949 if (!item.isDir)
950 {
847 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
951 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
848 if (meta) {
952 if (meta)
953 {
849 dl.innerHTML = `
954 dl.innerHTML = `
850 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
955 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
851 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
956 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
@@ -859,7 +964,8 @@ async function openSidebar(item) {
859 btnDl.textContent = 'View / Download';
964 btnDl.textContent = 'View / Download';
860 btnDl.addEventListener('click', () => downloadOrView(item));
965 btnDl.addEventListener('click', () => downloadOrView(item));
861 actions.appendChild(btnDl);
966 actions.appendChild(btnDl);
862 } else {
967 } else
968 {
863 dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`;
969 dl.innerHTML = `<dt>Type</dt><dd>Folder</dd>`;
864 const btnOpen = document.createElement('button');
970 const btnOpen = document.createElement('button');
865 btnOpen.textContent = 'Open folder';
971 btnOpen.textContent = 'Open folder';
@@ -868,7 +974,8 @@ async function openSidebar(item) {
868 }
974 }
869
975
870 // Rename button (write access required)
976 // Rename button (write access required)
871 if (canWrite()) {
977 if (canWrite())
978 {
872 const btnRen = document.createElement('button');
979 const btnRen = document.createElement('button');
873 btnRen.textContent = 'Rename';
980 btnRen.textContent = 'Rename';
874 btnRen.addEventListener('click', () => openRenameModal(item));
981 btnRen.addEventListener('click', () => openRenameModal(item));
@@ -876,13 +983,14 @@ async function openSidebar(item) {
876
983
877 const btnDel = document.createElement('button');
984 const btnDel = document.createElement('button');
878 btnDel.textContent = 'Delete';
985 btnDel.textContent = 'Delete';
879 btnDel.className = 'danger';
986 btnDel.className = 'danger';
880 btnDel.addEventListener('click', () => deleteItem(item));
987 btnDel.addEventListener('click', () => deleteItem(item));
881 actions.appendChild(btnDel);
988 actions.appendChild(btnDel);
882 }
989 }
883}
990}
884
991
885function closeSidebar() {
992function closeSidebar ()
993{
886 document.getElementById('sidebar').classList.add('hidden');
994 document.getElementById('sidebar').classList.add('hidden');
887 document.getElementById('app').classList.remove('sidebar-open');
995 document.getElementById('app').classList.remove('sidebar-open');
888 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
996 document.querySelectorAll('.file-item.selected').forEach(e => e.classList.remove('selected'));
@@ -893,40 +1001,46 @@ function closeSidebar() {
893// DOWNLOAD / VIEW
1001// DOWNLOAD / VIEW
894// ───────────────────────────────────────────────────────────────────────────
1002// ───────────────────────────────────────────────────────────────────────────
895
1003
896function downloadOrView(item) {
1004function downloadOrView (item)
1005{
897 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
1006 const url = `/api/files/download?file=${encodeURIComponent(item.path)}`;
898 // Open in new tab — browser decides whether to display or download
1007 // Open in new tab — browser decides whether to display or download
899 const a = document.createElement('a');
1008 const a = document.createElement('a');
900 a.href = url;
1009 a.href = url;
901 a.target = '_blank';
1010 a.target = '_blank';
902 a.rel = 'noopener noreferrer';
1011 a.rel = 'noopener noreferrer';
903 // We need to send the auth header; since <a> can't do that, we fetch and blob it
1012 // We need to send the auth header; since <a> can't do that, we fetch and blob it
904 fetchAndServe(item, url);
1013 fetchAndServe(item, url);
905}
1014}
906
1015
907async function fetchAndServe(item, url) {
1016async function fetchAndServe (item, url)
908 try {
1017{
1018 try
1019 {
909 const res = await fetch(url, {
1020 const res = await fetch(url, {
910 headers: {
1021 headers: {
911 Authorization: 'Bearer ' + STATE.token,
1022 Authorization: 'Bearer ' + STATE.token,
912 'X-Fp': getFingerprint(),
1023 'X-Fp': getFingerprint(),
913 },
1024 },
914 });
1025 });
915 if (!res.ok) { toast('Download failed.', 'err'); return; }
1026 if (!res.ok) { toast('Download failed.', 'err'); return; }
916 const blob = await res.blob();
1027 const blob = await res.blob();
917 const objUrl = URL.createObjectURL(blob);
1028 const objUrl = URL.createObjectURL(blob);
918 const a = document.createElement('a');
1029 const a = document.createElement('a');
919 a.href = objUrl;
1030 a.href = objUrl;
920 a.download = item.name;
1031 a.download = item.name;
921 // Try to open viewable types inline
1032 // Try to open viewable types inline
922 const viewable = /^(image|video|audio|text|application\/pdf)/.test(blob.type);
1033 const viewable = /^(image|video|audio|text|application\/pdf)/.test(blob.type);
923 if (viewable) {
1034 if (viewable)
1035 {
924 window.open(objUrl, '_blank', 'noopener,noreferrer');
1036 window.open(objUrl, '_blank', 'noopener,noreferrer');
925 } else {
1037 } else
1038 {
926 a.click();
1039 a.click();
927 }
1040 }
928 setTimeout(() => URL.revokeObjectURL(objUrl), 60000);
1041 setTimeout(() => URL.revokeObjectURL(objUrl), 60000);
929 } catch {
1042 } catch
1043 {
930 toast('Download failed.', 'err');
1044 toast('Download failed.', 'err');
931 }
1045 }
932}
1046}
@@ -935,16 +1049,18 @@ async function fetchAndServe(item, url) {
935// UPLOAD
1049// UPLOAD
936// ───────────────────────────────────────────────────────────────────────────
1050// ───────────────────────────────────────────────────────────────────────────
937
1051
938function canWrite() {
1052function canWrite ()
1053{
939 if (STATE.isAdmin) return true;
1054 if (STATE.isAdmin) return true;
940 if (!STATE.currentRoot) return false;
1055 if (!STATE.currentRoot) return false;
941 const p = STATE.permissions[STATE.currentRoot.label];
1056 const p = STATE.permissions[STATE.currentRoot.label];
942 return p && p.write;
1057 return p && p.write;
943}
1058}
944
1059
945async function uploadFiles(fileList) {
1060async function uploadFiles (fileList)
1061{
946 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1062 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
947 if (!canWrite()) { toast('No write access.', 'err'); return; }
1063 if (!canWrite()) { toast('No write access.', 'err'); return; }
948
1064
949 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
1065 const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
950 const formData = new FormData();
1066 const formData = new FormData();
@@ -957,21 +1073,26 @@ async function uploadFiles(fileList) {
957 document.body.appendChild(wrap);
1073 document.body.appendChild(wrap);
958 STATE.uploadInProgress = true;
1074 STATE.uploadInProgress = true;
959
1075
960 try {
1076 try
1077 {
961 const xhr = new XMLHttpRequest();
1078 const xhr = new XMLHttpRequest();
962 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
1079 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
963 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1080 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
964 xhr.setRequestHeader('X-Fp', getFingerprint());
1081 xhr.setRequestHeader('X-Fp', getFingerprint());
965 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
1082 xhr.setRequestHeader('X-Upload-Size', String(totalSize));
966
1083
967 xhr.upload.addEventListener('progress', e => {
1084 xhr.upload.addEventListener('progress', e =>
968 if (e.lengthComputable) {
1085 {
1086 if (e.lengthComputable)
1087 {
969 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
1088 wrap.querySelector('.upload-bar-fill').style.width = (e.loaded / e.total * 100) + '%';
970 }
1089 }
971 });
1090 });
972
1091
973 await new Promise((resolve, reject) => {
1092 await new Promise((resolve, reject) =>
974 xhr.onload = () => {
1093 {
1094 xhr.onload = () =>
1095 {
975 if (xhr.status === 200) resolve();
1096 if (xhr.status === 200) resolve();
976 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
1097 else reject(new Error(JSON.parse(xhr.responseText).error || 'Upload failed'));
977 };
1098 };
@@ -981,19 +1102,23 @@ async function uploadFiles(fileList) {
981
1102
982 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
1103 toast(`Uploaded ${fileList.length} file(s).`, 'ok');
983 await navigateTo(STATE.currentDir, STATE.currentRoot);
1104 await navigateTo(STATE.currentDir, STATE.currentRoot);
984 } catch (err) {
1105 } catch (err)
1106 {
985 toast(err.message, 'err');
1107 toast(err.message, 'err');
986 } finally {
1108 } finally
1109 {
987 STATE.uploadInProgress = false;
1110 STATE.uploadInProgress = false;
988 wrap.remove();
1111 wrap.remove();
989 }
1112 }
990}
1113}
991
1114
992async function uploadSingleFile(file, targetDir) {
1115async function uploadSingleFile (file, targetDir)
1116{
993 const formData = new FormData();
1117 const formData = new FormData();
994 formData.append('files', file);
1118 formData.append('files', file);
995
1119
996 await new Promise((resolve, reject) => {
1120 await new Promise((resolve, reject) =>
1121 {
997 const xhr = new XMLHttpRequest();
1122 const xhr = new XMLHttpRequest();
998 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
1123 xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
999 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1124 xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
@@ -1007,14 +1132,18 @@ async function uploadSingleFile(file, targetDir) {
1007 });
1132 });
1008}
1133}
1009
1134
1010async function ensureServerDir(baseDir, relativeDir) {
1135async function ensureServerDir (baseDir, relativeDir)
1136{
1011 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
1137 const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
1012 let current = baseDir;
1138 let current = baseDir;
1013 for (const part of parts) {
1139 for (const part of parts)
1014 try {
1140 {
1141 try
1142 {
1015 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
1143 const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
1016 current = resp && resp.path ? resp.path : joinServerPath(current, part);
1144 current = resp && resp.path ? resp.path : joinServerPath(current, part);
1017 } catch (err) {
1145 } catch (err)
1146 {
1018 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1147 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1019 current = joinServerPath(current, part);
1148 current = joinServerPath(current, part);
1020 }
1149 }
@@ -1022,9 +1151,10 @@ async function ensureServerDir(baseDir, relativeDir) {
1022 return current;
1151 return current;
1023}
1152}
1024
1153
1025async function uploadFolderInputFiles(fileList) {
1154async function uploadFolderInputFiles (fileList)
1155{
1026 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1156 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1027 if (!canWrite()) { toast('No write access.', 'err'); return; }
1157 if (!canWrite()) { toast('No write access.', 'err'); return; }
1028 if (!fileList || !fileList.length) return;
1158 if (!fileList || !fileList.length) return;
1029
1159
1030 const files = Array.from(fileList);
1160 const files = Array.from(fileList);
@@ -1037,24 +1167,29 @@ async function uploadFolderInputFiles(fileList) {
1037 document.body.appendChild(wrap);
1167 document.body.appendChild(wrap);
1038 STATE.uploadInProgress = true;
1168 STATE.uploadInProgress = true;
1039
1169
1040 try {
1170 try
1171 {
1041 const dirCache = new Map();
1172 const dirCache = new Map();
1042 dirCache.set('', STATE.currentDir);
1173 dirCache.set('', STATE.currentDir);
1043
1174
1044 for (const file of files) {
1175 for (const file of files)
1176 {
1045 const rel = file.webkitRelativePath || file.name;
1177 const rel = file.webkitRelativePath || file.name;
1046 const relParts = rel.split(/[\\/]/).filter(Boolean);
1178 const relParts = rel.split(/[\\/]/).filter(Boolean);
1047 const relDir = relParts.slice(0, -1).join('/');
1179 const relDir = relParts.slice(0, -1).join('/');
1048
1180
1049 if (!dirCache.has(relDir)) {
1181 if (!dirCache.has(relDir))
1182 {
1050 const parentRel = relParts.slice(0, -2).join('/');
1183 const parentRel = relParts.slice(0, -2).join('/');
1051 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
1184 const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
1052 const thisName = relParts[relParts.length - 2];
1185 const thisName = relParts[relParts.length - 2];
1053
1186
1054 try {
1187 try
1188 {
1055 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
1189 const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
1056 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
1190 dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
1057 } catch (err) {
1191 } catch (err)
1192 {
1058 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1193 if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1059 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
1194 dirCache.set(relDir, joinServerPath(parentAbs, thisName));
1060 }
1195 }
@@ -1069,9 +1204,11 @@ async function uploadFolderInputFiles(fileList) {
1069
1204
1070 toast(`Uploaded ${total} file(s).`, 'ok');
1205 toast(`Uploaded ${total} file(s).`, 'ok');
1071 await navigateTo(STATE.currentDir, STATE.currentRoot);
1206 await navigateTo(STATE.currentDir, STATE.currentRoot);
1072 } catch (err) {
1207 } catch (err)
1208 {
1073 toast(err.message, 'err');
1209 toast(err.message, 'err');
1074 } finally {
1210 } finally
1211 {
1075 STATE.uploadInProgress = false;
1212 STATE.uploadInProgress = false;
1076 wrap.remove();
1213 wrap.remove();
1077 }
1214 }
@@ -1085,11 +1222,15 @@ async function uploadFolderInputFiles(fileList) {
1085 * Reads all readEntries batches from a DirectoryReader (browsers may return
1222 * Reads all readEntries batches from a DirectoryReader (browsers may return
1086 * results in chunks; we must keep calling until we get an empty array).
1223 * results in chunks; we must keep calling until we get an empty array).
1087 */
1224 */
1088function readAllEntries(reader) {
1225function readAllEntries (reader)
1089 return new Promise((resolve, reject) => {
1226{
1227 return new Promise((resolve, reject) =>
1228 {
1090 const all = [];
1229 const all = [];
1091 function next() {
1230 function next ()
1092 reader.readEntries(batch => {
1231 {
1232 reader.readEntries(batch =>
1233 {
1093 if (!batch.length) { resolve(all); return; }
1234 if (!batch.length) { resolve(all); return; }
1094 all.push(...batch);
1235 all.push(...batch);
1095 next();
1236 next();
@@ -1103,17 +1244,22 @@ function readAllEntries(reader) {
1103 * Recursively walk a FileSystemEntry tree, creating server-side directories
1244 * Recursively walk a FileSystemEntry tree, creating server-side directories
1104 * on the fly and collecting { file, targetDir } pairs for upload.
1245 * on the fly and collecting { file, targetDir } pairs for upload.
1105 */
1246 */
1106async function collectEntries(entry, serverDir, toUpload) {
1247async function collectEntries (entry, serverDir, toUpload)
1107 if (entry.isFile) {
1248{
1249 if (entry.isFile)
1250 {
1108 const file = await new Promise((res, rej) => entry.file(res, rej));
1251 const file = await new Promise((res, rej) => entry.file(res, rej));
1109 toUpload.push({ file, targetDir: serverDir });
1252 toUpload.push({ file, targetDir: serverDir });
1110 } else if (entry.isDirectory) {
1253 } else if (entry.isDirectory)
1254 {
1111 // Ask the server to create the directory; it returns the canonical path.
1255 // Ask the server to create the directory; it returns the canonical path.
1112 let newServerDir;
1256 let newServerDir;
1113 try {
1257 try
1258 {
1114 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
1259 const resp = await api('POST', '/files/mkdir', { dir: serverDir, name: entry.name });
1115 newServerDir = resp.path;
1260 newServerDir = resp.path;
1116 } catch {
1261 } catch
1262 {
1117 // Directory may already exist — reconstruct path from what we know.
1263 // Directory may already exist — reconstruct path from what we know.
1118 // The server always returns JSON with {error} on failure, so we can
1264 // The server always returns JSON with {error} on failure, so we can
1119 // still continue by falling back to a best-effort path join.
1265 // still continue by falling back to a best-effort path join.
@@ -1124,15 +1270,17 @@ async function collectEntries(entry, serverDir, toUpload) {
1124 }
1270 }
1125 const reader = entry.createReader();
1271 const reader = entry.createReader();
1126 const subEntries = await readAllEntries(reader);
1272 const subEntries = await readAllEntries(reader);
1127 for (const sub of subEntries) {
1273 for (const sub of subEntries)
1274 {
1128 await collectEntries(sub, newServerDir, toUpload);
1275 await collectEntries(sub, newServerDir, toUpload);
1129 }
1276 }
1130 }
1277 }
1131}
1278}
1132
1279
1133async function uploadEntries(entries) {
1280async function uploadEntries (entries)
1281{
1134 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1282 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1135 if (!canWrite()) { toast('No write access.', 'err'); return; }
1283 if (!canWrite()) { toast('No write access.', 'err'); return; }
1136
1284
1137 const wrap = document.createElement('div');
1285 const wrap = document.createElement('div');
1138 wrap.className = 'upload-bar-wrap';
1286 wrap.className = 'upload-bar-wrap';
@@ -1140,9 +1288,11 @@ async function uploadEntries(entries) {
1140 document.body.appendChild(wrap);
1288 document.body.appendChild(wrap);
1141 STATE.uploadInProgress = true;
1289 STATE.uploadInProgress = true;
1142
1290
1143 try {
1291 try
1292 {
1144 const toUpload = [];
1293 const toUpload = [];
1145 for (const entry of entries) {
1294 for (const entry of entries)
1295 {
1146 await collectEntries(entry, STATE.currentDir, toUpload);
1296 await collectEntries(entry, STATE.currentDir, toUpload);
1147 }
1297 }
1148
1298
@@ -1150,13 +1300,15 @@ async function uploadEntries(entries) {
1150
1300
1151 let done = 0;
1301 let done = 0;
1152 const total = toUpload.length;
1302 const total = toUpload.length;
1153 const updateBar = () => {
1303 const updateBar = () =>
1304 {
1154 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1305 wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1155 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1306 wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1156 };
1307 };
1157 updateBar();
1308 updateBar();
1158
1309
1159 for (const { file, targetDir } of toUpload) {
1310 for (const { file, targetDir } of toUpload)
1311 {
1160 await uploadSingleFile(file, targetDir);
1312 await uploadSingleFile(file, targetDir);
1161 done++;
1313 done++;
1162 updateBar();
1314 updateBar();
@@ -1164,9 +1316,11 @@ async function uploadEntries(entries) {
1164
1316
1165 toast(`Uploaded ${total} file(s).`, 'ok');
1317 toast(`Uploaded ${total} file(s).`, 'ok');
1166 await navigateTo(STATE.currentDir, STATE.currentRoot);
1318 await navigateTo(STATE.currentDir, STATE.currentRoot);
1167 } catch (err) {
1319 } catch (err)
1320 {
1168 toast(err.message, 'err');
1321 toast(err.message, 'err');
1169 } finally {
1322 } finally
1323 {
1170 STATE.uploadInProgress = false;
1324 STATE.uploadInProgress = false;
1171 wrap.remove();
1325 wrap.remove();
1172 }
1326 }
@@ -1175,22 +1329,26 @@ async function uploadEntries(entries) {
1175// DRAG-AND-DROP
1329// DRAG-AND-DROP
1176// ───────────────────────────────────────────────────────────────────────────
1330// ───────────────────────────────────────────────────────────────────────────
1177
1331
1178function initDragDrop() {
1332function initDragDrop ()
1179 const main = document.getElementById('main-content');
1333{
1334 const main = document.getElementById('main-content');
1180 const dropOvl = document.getElementById('drop-overlay');
1335 const dropOvl = document.getElementById('drop-overlay');
1181 let dragDepth = 0;
1336 let dragDepth = 0;
1182
1337
1183 main.addEventListener('dragenter', e => {
1338 main.addEventListener('dragenter', e =>
1339 {
1184 e.preventDefault();
1340 e.preventDefault();
1185 dragDepth++;
1341 dragDepth++;
1186 dropOvl.classList.remove('hidden');
1342 dropOvl.classList.remove('hidden');
1187 });
1343 });
1188 main.addEventListener('dragleave', () => {
1344 main.addEventListener('dragleave', () =>
1345 {
1189 dragDepth--;
1346 dragDepth--;
1190 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
1347 if (dragDepth <= 0) { dragDepth = 0; dropOvl.classList.add('hidden'); }
1191 });
1348 });
1192 main.addEventListener('dragover', e => e.preventDefault());
1349 main.addEventListener('dragover', e => e.preventDefault());
1193 main.addEventListener('drop', async e => {
1350 main.addEventListener('drop', async e =>
1351 {
1194 e.preventDefault();
1352 e.preventDefault();
1195 dragDepth = 0;
1353 dragDepth = 0;
1196 dropOvl.classList.add('hidden');
1354 dropOvl.classList.add('hidden');
@@ -1198,9 +1356,11 @@ function initDragDrop() {
1198
1356
1199 const items = Array.from(e.dataTransfer.items || []);
1357 const items = Array.from(e.dataTransfer.items || []);
1200 // Use the FileSystem Entry API when available so we can handle folders.
1358 // Use the FileSystem Entry API when available so we can handle folders.
1201 if (items.length && typeof items[0].webkitGetAsEntry === 'function') {
1359 if (items.length && typeof items[0].webkitGetAsEntry === 'function')
1360 {
1202 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
1361 const entries = items.map(i => i.webkitGetAsEntry()).filter(Boolean);
1203 if (entries.some(en => en.isDirectory)) {
1362 if (entries.some(en => en.isDirectory))
1363 {
1204 await uploadEntries(entries);
1364 await uploadEntries(entries);
1205 return;
1365 return;
1206 }
1366 }
@@ -1215,7 +1375,8 @@ function initDragDrop() {
1215// RENAME
1375// RENAME
1216// ───────────────────────────────────────────────────────────────────────────
1376// ───────────────────────────────────────────────────────────────────────────
1217
1377
1218function openRenameModal(item) {
1378function openRenameModal (item)
1379{
1219 const modal = document.getElementById('rename-modal');
1380 const modal = document.getElementById('rename-modal');
1220 modal.classList.remove('hidden');
1381 modal.classList.remove('hidden');
1221 const input = document.getElementById('rename-input');
1382 const input = document.getElementById('rename-input');
@@ -1223,16 +1384,19 @@ function openRenameModal(item) {
1223 input.focus();
1384 input.focus();
1224 input.select();
1385 input.select();
1225 document.getElementById('rename-error').classList.add('hidden');
1386 document.getElementById('rename-error').classList.add('hidden');
1226 document.getElementById('rename-form').onsubmit = async (e) => {
1387 document.getElementById('rename-form').onsubmit = async (e) =>
1388 {
1227 e.preventDefault();
1389 e.preventDefault();
1228 const newName = input.value.trim();
1390 const newName = input.value.trim();
1229 if (!newName) return;
1391 if (!newName) return;
1230 try {
1392 try
1393 {
1231 await api('POST', '/files/rename', { from: item.path, to: newName });
1394 await api('POST', '/files/rename', { from: item.path, to: newName });
1232 modal.classList.add('hidden');
1395 modal.classList.add('hidden');
1233 toast('Renamed.', 'ok');
1396 toast('Renamed.', 'ok');
1234 await navigateTo(STATE.currentDir, STATE.currentRoot);
1397 await navigateTo(STATE.currentDir, STATE.currentRoot);
1235 } catch (err) {
1398 } catch (err)
1399 {
1236 document.getElementById('rename-error').textContent = err.message;
1400 document.getElementById('rename-error').textContent = err.message;
1237 document.getElementById('rename-error').classList.remove('hidden');
1401 document.getElementById('rename-error').classList.remove('hidden');
1238 }
1402 }
@@ -1243,14 +1407,17 @@ function openRenameModal(item) {
1243// DELETE
1407// DELETE
1244// ───────────────────────────────────────────────────────────────────────────
1408// ───────────────────────────────────────────────────────────────────────────
1245
1409
1246async function deleteItem(item) {
1410async function deleteItem (item)
1411{
1247 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
1412 if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
1248 try {
1413 try
1414 {
1249 await api('POST', '/files/delete', { path: item.path });
1415 await api('POST', '/files/delete', { path: item.path });
1250 toast('Deleted.', 'ok');
1416 toast('Deleted.', 'ok');
1251 closeSidebar();
1417 closeSidebar();
1252 await navigateTo(STATE.currentDir, STATE.currentRoot);
1418 await navigateTo(STATE.currentDir, STATE.currentRoot);
1253 } catch (err) {
1419 } catch (err)
1420 {
1254 toast(err.message, 'err');
1421 toast(err.message, 'err');
1255 }
1422 }
1256}
1423}
@@ -1259,29 +1426,34 @@ async function deleteItem(item) {
1259// ADMIN PANEL
1426// ADMIN PANEL
1260// ───────────────────────────────────────────────────────────────────────────
1427// ───────────────────────────────────────────────────────────────────────────
1261
1428
1262async function openAdminModal() {
1429async function openAdminModal ()
1430{
1263 document.getElementById('admin-modal').classList.remove('hidden');
1431 document.getElementById('admin-modal').classList.remove('hidden');
1264 await refreshAdminConfig();
1432 await refreshAdminConfig();
1265 await refreshAdminUsers();
1433 await refreshAdminUsers();
1266}
1434}
1267
1435
1268async function refreshAdminConfig() {
1436async function refreshAdminConfig ()
1437{
1269 const data = await api('GET', '/admin/config');
1438 const data = await api('GET', '/admin/config');
1270 if (!data) return;
1439 if (!data) return;
1271 const container = document.getElementById('admin-paths');
1440 const container = document.getElementById('admin-paths');
1272 container.innerHTML = '';
1441 container.innerHTML = '';
1273 for (const p of data.paths) {
1442 for (const p of data.paths)
1443 {
1274 const row = document.createElement('div');
1444 const row = document.createElement('div');
1275 row.className = 'path-row';
1445 row.className = 'path-row';
1276 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
1446 row.innerHTML = `<span>${p}</span><button data-path="${p}" title="Remove">✕</button>`;
1277 row.querySelector('button').addEventListener('click', () => {
1447 row.querySelector('button').addEventListener('click', () =>
1448 {
1278 row.remove();
1449 row.remove();
1279 });
1450 });
1280 container.appendChild(row);
1451 container.appendChild(row);
1281 }
1452 }
1282}
1453}
1283
1454
1284async function refreshAdminUsers() {
1455async function refreshAdminUsers ()
1456{
1285 const data = await api('GET', '/admin/users');
1457 const data = await api('GET', '/admin/users');
1286 if (!data) return;
1458 if (!data) return;
1287 const container = document.getElementById('admin-users-list');
1459 const container = document.getElementById('admin-users-list');
@@ -1291,7 +1463,8 @@ async function refreshAdminUsers() {
1291 const cfg = await api('GET', '/admin/config');
1463 const cfg = await api('GET', '/admin/config');
1292 const paths = cfg ? (cfg.effectivePaths || []) : [];
1464 const paths = cfg ? (cfg.effectivePaths || []) : [];
1293
1465
1294 for (const u of data.users) {
1466 for (const u of data.users)
1467 {
1295 const row = document.createElement('div');
1468 const row = document.createElement('div');
1296 row.className = 'user-row';
1469 row.className = 'user-row';
1297 row.innerHTML = `
1470 row.innerHTML = `
@@ -1302,9 +1475,11 @@ async function refreshAdminUsers() {
1302 `;
1475 `;
1303 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
1476 row.querySelector('[data-action="edit"]').addEventListener('click', () =>
1304 openUserModal(u, paths));
1477 openUserModal(u, paths));
1305 row.querySelector('[data-action="delete"]').addEventListener('click', async () => {
1478 row.querySelector('[data-action="delete"]').addEventListener('click', async () =>
1479 {
1306 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
1480 if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
1307 try {
1481 try
1482 {
1308 await api('DELETE', `/admin/users/${u.id}`);
1483 await api('DELETE', `/admin/users/${u.id}`);
1309 toast('User deleted.', 'ok');
1484 toast('User deleted.', 'ok');
1310 await refreshAdminUsers();
1485 await refreshAdminUsers();
@@ -1314,17 +1489,18 @@ async function refreshAdminUsers() {
1314 }
1489 }
1315}
1490}
1316
1491
1317function openUserModal(user, paths) {
1492function openUserModal (user, paths)
1493{
1318 const modal = document.getElementById('user-modal');
1494 const modal = document.getElementById('user-modal');
1319 modal.classList.remove('hidden');
1495 modal.classList.remove('hidden');
1320 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
1496 document.getElementById('user-modal-title').textContent = user ? `Edit: ${user.username}` : 'New User';
1321 document.getElementById('user-error').classList.add('hidden');
1497 document.getElementById('user-error').classList.add('hidden');
1322
1498
1323 const usernameInput = document.getElementById('user-username');
1499 const usernameInput = document.getElementById('user-username');
1324 usernameInput.value = user ? user.username : '';
1500 usernameInput.value = user ? user.username : '';
1325 usernameInput.readOnly = !!user;
1501 usernameInput.readOnly = !!user;
1326
1502
1327 document.getElementById('user-password').value = '';
1503 document.getElementById('user-password').value = '';
1328 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
1504 document.getElementById('user-is-admin').checked = user ? user.isAdmin : false;
1329
1505
1330 // Password placeholder
1506 // Password placeholder
@@ -1334,7 +1510,8 @@ function openUserModal(user, paths) {
1334 // Build permissions grid
1510 // Build permissions grid
1335 const permDiv = document.getElementById('user-permissions');
1511 const permDiv = document.getElementById('user-permissions');
1336 permDiv.innerHTML = '';
1512 permDiv.innerHTML = '';
1337 if (paths.length) {
1513 if (paths.length)
1514 {
1338 const heading = document.createElement('h4');
1515 const heading = document.createElement('h4');
1339 heading.textContent = 'Path Permissions';
1516 heading.textContent = 'Path Permissions';
1340 permDiv.appendChild(heading);
1517 permDiv.appendChild(heading);
@@ -1342,9 +1519,12 @@ function openUserModal(user, paths) {
1342 const isAdminUser = !!(user && user.isAdmin);
1519 const isAdminUser = !!(user && user.isAdmin);
1343 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
1520 // Mirror the is-admin checkbox so toggling it live-updates the perm rows.
1344 const adminChk = document.getElementById('user-is-admin');
1521 const adminChk = document.getElementById('user-is-admin');
1345 const rebuildPermRows = (admin) => {
1522 const rebuildPermRows = (admin) =>
1346 permDiv.querySelectorAll('.perm-row').forEach(r => {
1523 {
1347 r.querySelectorAll('input[type=checkbox]').forEach(cb => {
1524 permDiv.querySelectorAll('.perm-row').forEach(r =>
1525 {
1526 r.querySelectorAll('input[type=checkbox]').forEach(cb =>
1527 {
1348 cb.disabled = admin;
1528 cb.disabled = admin;
1349 if (admin) cb.checked = true;
1529 if (admin) cb.checked = true;
1350 });
1530 });
@@ -1353,12 +1533,13 @@ function openUserModal(user, paths) {
1353 };
1533 };
1354 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
1534 adminChk.addEventListener('change', () => rebuildPermRows(adminChk.checked));
1355
1535
1356 for (const p of paths) {
1536 for (const p of paths)
1357 const label = p.split(/[\\/]/).pop();
1537 {
1358 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
1538 const label = p.split(/[\\/]/).pop();
1359 const row = document.createElement('div');
1539 const perms = user && user.permissions ? (user.permissions[label] || {}) : {};
1540 const row = document.createElement('div');
1360 row.className = 'perm-row';
1541 row.className = 'perm-row';
1361 const readChecked = isAdminUser || perms.read;
1542 const readChecked = isAdminUser || perms.read;
1362 const writeChecked = isAdminUser || perms.write;
1543 const writeChecked = isAdminUser || perms.write;
1363 row.innerHTML = `
1544 row.innerHTML = `
1364 <span class="perm-label">${label}</span>
1545 <span class="perm-label">${label}</span>
@@ -1370,30 +1551,36 @@ function openUserModal(user, paths) {
1370 }
1551 }
1371 }
1552 }
1372
1553
1373 document.getElementById('user-form').onsubmit = async (e) => {
1554 document.getElementById('user-form').onsubmit = async (e) =>
1555 {
1374 e.preventDefault();
1556 e.preventDefault();
1375 const password = document.getElementById('user-password').value;
1557 const password = document.getElementById('user-password').value;
1376 const isAdmin = document.getElementById('user-is-admin').checked;
1558 const isAdmin = document.getElementById('user-is-admin').checked;
1377 const permissions = {};
1559 const permissions = {};
1378 permDiv.querySelectorAll('input[data-label]').forEach(cb => {
1560 permDiv.querySelectorAll('input[data-label]').forEach(cb =>
1561 {
1379 const lbl = cb.dataset.label;
1562 const lbl = cb.dataset.label;
1380 if (!permissions[lbl]) permissions[lbl] = {};
1563 if (!permissions[lbl]) permissions[lbl] = {};
1381 permissions[lbl][cb.dataset.type] = cb.checked;
1564 permissions[lbl][cb.dataset.type] = cb.checked;
1382 });
1565 });
1383
1566
1384 try {
1567 try
1385 if (user) {
1568 {
1569 if (user)
1570 {
1386 const body = { isAdmin, permissions };
1571 const body = { isAdmin, permissions };
1387 if (password) body.password = password;
1572 if (password) body.password = password;
1388 await api('PATCH', `/admin/users/${user.id}`, body);
1573 await api('PATCH', `/admin/users/${user.id}`, body);
1389 } else {
1574 } else
1575 {
1390 const uname = document.getElementById('user-username').value.trim();
1576 const uname = document.getElementById('user-username').value.trim();
1391 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
1577 await api('POST', '/admin/users', { username: uname, password, isAdmin, permissions });
1392 }
1578 }
1393 modal.classList.add('hidden');
1579 modal.classList.add('hidden');
1394 toast('User saved.', 'ok');
1580 toast('User saved.', 'ok');
1395 await refreshAdminUsers();
1581 await refreshAdminUsers();
1396 } catch (err) {
1582 } catch (err)
1583 {
1397 document.getElementById('user-error').textContent = err.message;
1584 document.getElementById('user-error').textContent = err.message;
1398 document.getElementById('user-error').classList.remove('hidden');
1585 document.getElementById('user-error').classList.remove('hidden');
1399 }
1586 }
@@ -1404,31 +1591,33 @@ function openUserModal(user, paths) {
1404// SVG ICONS
1591// SVG ICONS
1405// ───────────────────────────────────────────────────────────────────────────
1592// ───────────────────────────────────────────────────────────────────────────
1406
1593
1407const IMAGE_EXTS = new Set(['jpg','jpeg','png','gif','webp','svg','bmp','ico','avif']);
1594const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'ico', 'avif']);
1408const VIDEO_EXTS = new Set(['mp4','webm','ogv','mov','avi','mkv']);
1595const VIDEO_EXTS = new Set(['mp4', 'webm', 'ogv', 'mov', 'avi', 'mkv']);
1409const AUDIO_EXTS = new Set(['mp3','ogg','wav','flac','aac','m4a']);
1596const AUDIO_EXTS = new Set(['mp3', 'ogg', 'wav', 'flac', 'aac', 'm4a']);
1410const DOC_EXTS = new Set(['pdf','doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp']);
1597const DOC_EXTS = new Set(['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp']);
1411const CODE_EXTS = new Set(['js','ts','py','rb','go','rs','c','cpp','h','cs','java','php','html','css','json','xml','yaml','yml','sh','bash','md','txt']);
1598const CODE_EXTS = new Set(['js', 'ts', 'py', 'rb', 'go', 'rs', 'c', 'cpp', 'h', 'cs', 'java', 'php', 'html', 'css', 'json', 'xml', 'yaml', 'yml', 'sh', 'bash', 'md', 'txt']);
1412const ARCHIVE_EXTS= new Set(['zip','tar','gz','bz2','xz','rar','7z']);
1599const ARCHIVE_EXTS = new Set(['zip', 'tar', 'gz', 'bz2', 'xz', 'rar', '7z']);
1413
1600
1414function iconFolder(size = 52) {
1601function iconFolder (size = 52)
1602{
1415 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1603 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1416 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
1604 stroke="#5b7fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
1417 <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
1605 <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
1418 </svg>`;
1606 </svg>`;
1419}
1607}
1420
1608
1421function iconFile(name, size = 52) {
1609function iconFile (name, size = 52)
1422 const ext = extOf(name);
1610{
1423 let color = '#7880a0';
1611 const ext = extOf(name);
1424 let symbol = '';
1612 let color = '#7880a0';
1613 let symbol = '';
1425
1614
1426 if (IMAGE_EXTS.has(ext)) color = '#3fcf8e';
1615 if (IMAGE_EXTS.has(ext)) color = '#3fcf8e';
1427 else if (VIDEO_EXTS.has(ext)) color = '#e05c6e';
1616 else if (VIDEO_EXTS.has(ext)) color = '#e05c6e';
1428 else if (AUDIO_EXTS.has(ext)) color = '#c084fc';
1617 else if (AUDIO_EXTS.has(ext)) color = '#c084fc';
1429 else if (DOC_EXTS.has(ext)) color = '#f97316';
1618 else if (DOC_EXTS.has(ext)) color = '#f97316';
1430 else if (CODE_EXTS.has(ext)) color = '#38bdf8';
1619 else if (CODE_EXTS.has(ext)) color = '#38bdf8';
1431 else if (ARCHIVE_EXTS.has(ext))color = '#facc15';
1620 else if (ARCHIVE_EXTS.has(ext)) color = '#facc15';
1432
1621
1433 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1622 return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none"
1434 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
1623 stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
@@ -1441,22 +1630,25 @@ function iconFile(name, size = 52) {
1441// EVENT WIRING
1630// EVENT WIRING
1442// ───────────────────────────────────────────────────────────────────────────
1631// ───────────────────────────────────────────────────────────────────────────
1443
1632
1444function wireEvents() {
1633function wireEvents ()
1634{
1445 // Auth form
1635 // Auth form
1446 document.getElementById('auth-form').addEventListener('submit', async (e) => {
1636 document.getElementById('auth-form').addEventListener('submit', async (e) =>
1637 {
1447 e.preventDefault();
1638 e.preventDefault();
1448 const username = document.getElementById('auth-username').value.trim();
1639 const username = document.getElementById('auth-username').value.trim();
1449 const password = document.getElementById('auth-password').value;
1640 const password = document.getElementById('auth-password').value;
1450 const isSetup = e.target.dataset.mode === 'setup';
1641 const isSetup = e.target.dataset.mode === 'setup';
1451 const errEl = document.getElementById('auth-error');
1642 const errEl = document.getElementById('auth-error');
1452 const btn = document.getElementById('auth-submit');
1643 const btn = document.getElementById('auth-submit');
1453 btn.disabled = true;
1644 btn.disabled = true;
1454 btn.textContent = 'Please wait…';
1645 btn.textContent = 'Please wait…';
1455 const err = await doLogin(username, password, isSetup);
1646 const err = await doLogin(username, password, isSetup);
1456 if (err) {
1647 if (err)
1648 {
1457 errEl.textContent = err;
1649 errEl.textContent = err;
1458 errEl.classList.remove('hidden');
1650 errEl.classList.remove('hidden');
1459 btn.disabled = false;
1651 btn.disabled = false;
1460 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
1652 btn.textContent = isSetup ? 'Create Account' : 'Sign In';
1461 }
1653 }
1462 });
1654 });
@@ -1465,51 +1657,60 @@ function wireEvents() {
1465 document.getElementById('btn-logout').addEventListener('click', logout);
1657 document.getElementById('btn-logout').addEventListener('click', logout);
1466
1658
1467 // Hard refresh while keeping auth/session state.
1659 // Hard refresh while keeping auth/session state.
1468 document.getElementById('btn-refresh').addEventListener('click', () => {
1660 document.getElementById('btn-refresh').addEventListener('click', () =>
1661 {
1469 saveSessionState();
1662 saveSessionState();
1470 location.reload();
1663 location.reload();
1471 });
1664 });
1472
1665
1473 // Upload button
1666 // Upload button
1474 document.getElementById('btn-upload').addEventListener('click', () => {
1667 document.getElementById('btn-upload').addEventListener('click', () =>
1668 {
1475 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1669 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1476 if (!canWrite()) { toast('No write access.', 'err'); return; }
1670 if (!canWrite()) { toast('No write access.', 'err'); return; }
1477 document.getElementById('file-input').click();
1671 document.getElementById('file-input').click();
1478 });
1672 });
1479
1673
1480 document.getElementById('file-input').addEventListener('change', async (e) => {
1674 document.getElementById('file-input').addEventListener('change', async (e) =>
1675 {
1481 if (e.target.files.length) await uploadFiles(e.target.files);
1676 if (e.target.files.length) await uploadFiles(e.target.files);
1482 e.target.value = '';
1677 e.target.value = '';
1483 });
1678 });
1484
1679
1485 document.getElementById('btn-upload-folder').addEventListener('click', () => {
1680 document.getElementById('btn-upload-folder').addEventListener('click', () =>
1681 {
1486 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1682 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1487 if (!canWrite()) { toast('No write access.', 'err'); return; }
1683 if (!canWrite()) { toast('No write access.', 'err'); return; }
1488 document.getElementById('folder-input').click();
1684 document.getElementById('folder-input').click();
1489 });
1685 });
1490
1686
1491 document.getElementById('folder-input').addEventListener('change', async (e) => {
1687 document.getElementById('folder-input').addEventListener('change', async (e) =>
1688 {
1492 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
1689 if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
1493 e.target.value = '';
1690 e.target.value = '';
1494 });
1691 });
1495
1692
1496 document.getElementById('btn-new-folder').addEventListener('click', async () => {
1693 document.getElementById('btn-new-folder').addEventListener('click', async () =>
1694 {
1497 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1695 if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1498 if (!canWrite()) { toast('No write access.', 'err'); return; }
1696 if (!canWrite()) { toast('No write access.', 'err'); return; }
1499
1697
1500 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
1698 const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
1501 if (name == null) return;
1699 if (name == null) return;
1502 const folderName = name.trim();
1700 const folderName = name.trim();
1503 if (!folderName) {
1701 if (!folderName)
1702 {
1504 toast('Folder name is required.', 'err');
1703 toast('Folder name is required.', 'err');
1505 return;
1704 return;
1506 }
1705 }
1507
1706
1508 try {
1707 try
1708 {
1509 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
1709 await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
1510 toast('Folder created.', 'ok');
1710 toast('Folder created.', 'ok');
1511 await navigateTo(STATE.currentDir, STATE.currentRoot);
1711 await navigateTo(STATE.currentDir, STATE.currentRoot);
1512 } catch (err) {
1712 } catch (err)
1713 {
1513 toast(err.message, 'err');
1714 toast(err.message, 'err');
1514 }
1715 }
1515 });
1716 });
@@ -1518,7 +1719,8 @@ function wireEvents() {
1518 document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
1719 document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
1519
1720
1520 // Click outside grid closes sidebar
1721 // Click outside grid closes sidebar
1521 document.getElementById('main-content').addEventListener('click', (e) => {
1722 document.getElementById('main-content').addEventListener('click', (e) =>
1723 {
1522 if (!e.target.closest('.file-item')) closeSidebar();
1724 if (!e.target.closest('.file-item')) closeSidebar();
1523 });
1725 });
1524
1726
@@ -1528,7 +1730,8 @@ function wireEvents() {
1528 document.getElementById('admin-modal').classList.add('hidden'));
1730 document.getElementById('admin-modal').classList.add('hidden'));
1529
1731
1530 // Add path
1732 // Add path
1531 document.getElementById('admin-add-path').addEventListener('click', () => {
1733 document.getElementById('admin-add-path').addEventListener('click', () =>
1734 {
1532 const val = document.getElementById('admin-new-path').value.trim();
1735 const val = document.getElementById('admin-new-path').value.trim();
1533 if (!val) return;
1736 if (!val) return;
1534 const row = document.createElement('div');
1737 const row = document.createElement('div');
@@ -1540,10 +1743,12 @@ function wireEvents() {
1540 });
1743 });
1541
1744
1542 // Save paths
1745 // Save paths
1543 document.getElementById('admin-save-paths').addEventListener('click', async () => {
1746 document.getElementById('admin-save-paths').addEventListener('click', async () =>
1544 const rows = document.querySelectorAll('#admin-paths .path-row span');
1747 {
1748 const rows = document.querySelectorAll('#admin-paths .path-row span');
1545 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
1749 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
1546 try {
1750 try
1751 {
1547 await api('PUT', '/admin/config', { paths });
1752 await api('PUT', '/admin/config', { paths });
1548 toast('Paths saved.', 'ok');
1753 toast('Paths saved.', 'ok');
1549 await loadRoots();
1754 await loadRoots();
@@ -1551,13 +1756,16 @@ function wireEvents() {
1551 });
1756 });
1552
1757
1553 // Shutdown server
1758 // Shutdown server
1554 document.getElementById('admin-shutdown-btn').addEventListener('click', async () => {
1759 document.getElementById('admin-shutdown-btn').addEventListener('click', async () =>
1760 {
1555 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
1761 if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
1556 try {
1762 try
1763 {
1557 await api('POST', '/admin/shutdown');
1764 await api('POST', '/admin/shutdown');
1558 toast('Server is shutting down…', 'ok');
1765 toast('Server is shutting down…', 'ok');
1559 document.getElementById('admin-modal').classList.add('hidden');
1766 document.getElementById('admin-modal').classList.add('hidden');
1560 } catch {
1767 } catch
1768 {
1561 // Fetch may throw because the connection closes before a response arrives.
1769 // Fetch may throw because the connection closes before a response arrives.
1562 toast('Server is shutting down…', 'ok');
1770 toast('Server is shutting down…', 'ok');
1563 document.getElementById('admin-modal').classList.add('hidden');
1771 document.getElementById('admin-modal').classList.add('hidden');
@@ -1565,8 +1773,9 @@ function wireEvents() {
1565 });
1773 });
1566
1774
1567 // New user
1775 // New user
1568 document.getElementById('admin-new-user-btn').addEventListener('click', async () => {
1776 document.getElementById('admin-new-user-btn').addEventListener('click', async () =>
1569 const cfg = await api('GET', '/admin/config');
1777 {
1778 const cfg = await api('GET', '/admin/config');
1570 const paths = cfg ? (cfg.effectivePaths || []) : [];
1779 const paths = cfg ? (cfg.effectivePaths || []) : [];
1571 openUserModal(null, paths);
1780 openUserModal(null, paths);
1572 });
1781 });
@@ -1580,8 +1789,10 @@ function wireEvents() {
1580 document.getElementById('rename-modal').classList.add('hidden'));
1789 document.getElementById('rename-modal').classList.add('hidden'));
1581
1790
1582 // Close modals on backdrop click
1791 // Close modals on backdrop click
1583 document.querySelectorAll('.modal-overlay').forEach(overlay => {
1792 document.querySelectorAll('.modal-overlay').forEach(overlay =>
1584 overlay.addEventListener('click', e => {
1793 {
1794 overlay.addEventListener('click', e =>
1795 {
1585 if (e.target === overlay) overlay.classList.add('hidden');
1796 if (e.target === overlay) overlay.classList.add('hidden');
1586 });
1797 });
1587 });
1798 });
@@ -1591,7 +1802,8 @@ function wireEvents() {
1591// BOOT
1802// BOOT
1592// ───────────────────────────────────────────────────────────────────────────
1803// ───────────────────────────────────────────────────────────────────────────
1593
1804
1594(async function boot() {
1805(async function boot ()
1806{
1595 wireEvents();
1807 wireEvents();
1596 initDragDrop();
1808 initDragDrop();
1597 window.addEventListener('beforeunload', saveSessionState);
1809 window.addEventListener('beforeunload', saveSessionState);
public/index.html +219 −213
@@ -1,252 +1,258 @@
1 1 <!DOCTYPE html>
2 2 <html lang="en">
3
3 4 <head>
4 5 <meta charset="UTF-8" />
5 6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 7 <title>File Manager</title>
7 8 <link rel="stylesheet" href="style.css" />
8 9 </head>
10
9 11 <body>
10 12
11 <!-- =====================================================================
13 <!-- =====================================================================
12 14 LOGIN / SETUP OVERLAY
13 15 ====================================================================== -->
14 <div id="auth-overlay" class="overlay hidden">
15 <div class="auth-card">
16 <h1 id="auth-title">Sign In</h1>
17 <p id="auth-subtitle" class="auth-subtitle hidden">
18 No accounts exist yet. Create the first admin account.
19 </p>
20 <form id="auth-form" autocomplete="off">
21 <label>
22 Username
23 <input id="auth-username" type="text" autocomplete="off" required />
24 </label>
25 <label>
26 Password
27 <input id="auth-password" type="password" autocomplete="new-password" required />
28 </label>
29 <p id="auth-error" class="error hidden"></p>
30 <button type="submit" id="auth-submit">Sign In</button>
31 </form>
16 <div id="auth-overlay" class="overlay hidden">
17 <div class="auth-card">
18 <h1 id="auth-title">Sign In</h1>
19 <p id="auth-subtitle" class="auth-subtitle hidden">
20 No accounts exist yet. Create the first admin account.
21 </p>
22 <form id="auth-form" autocomplete="off">
23 <label>
24 Username
25 <input id="auth-username" type="text" autocomplete="off" required />
26 </label>
27 <label>
28 Password
29 <input id="auth-password" type="password" autocomplete="new-password" required />
30 </label>
31 <p id="auth-error" class="error hidden"></p>
32 <button type="submit" id="auth-submit">Sign In</button>
33 </form>
34 </div>
32 35 </div>
33 </div>
34 36
35 <!-- =====================================================================
37 <!-- =====================================================================
36 38 MAIN APP SHELL
37 39 ====================================================================== -->
38 <div id="app" class="hidden">
40 <div id="app" class="hidden">
39 41
40 <!-- TOP BAR -->
41 <header id="topbar">
42 <div id="breadcrumb-wrap">
43 <nav id="breadcrumb" aria-label="Breadcrumb"></nav>
44 </div>
45 <div id="topbar-actions">
46 <button id="btn-refresh" class="icon-btn" title="Refresh page" aria-label="Refresh page">
47 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
48 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
49 <polyline points="23 4 23 10 17 10"/>
50 <polyline points="1 20 1 14 7 14"/>
51 <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 4.36A9 9 0 0 0 20.49 15"/>
52 </svg>
53 Refresh
54 </button>
55
56 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
57 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
58 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
59 <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
60 <polyline points="17 8 12 3 7 8"/>
61 <line x1="12" y1="3" x2="12" y2="15"/>
62 </svg>
63 Upload
64 </button>
65 <input id="file-input" type="file" multiple class="hidden" aria-hidden="true" />
66 <input id="folder-input" type="file" webkitdirectory directory multiple class="hidden" aria-hidden="true" />
67
68 <button id="btn-upload-folder" class="icon-btn" title="Upload folder" aria-label="Upload folder">
69 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
70 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
71 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
72 <path d="M12 11v6"/>
73 <path d="M9 14h6"/>
74 </svg>
75 Folder
76 </button>
77
78 <button id="btn-new-folder" class="icon-btn" title="Create new folder" aria-label="Create new folder">
79 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
80 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
81 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
82 <path d="M12 11v6"/>
83 <path d="M9 14h6"/>
84 </svg>
85 New Folder
86 </button>
87
88 <button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">
89 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
90 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
91 <circle cx="12" cy="8" r="4"/>
92 <path d="M6 20v-2a6 6 0 0 1 12 0v2"/>
93 </svg>
94 Admin
95 </button>
96
97 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
98 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
99 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
100 <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
101 <polyline points="16 17 21 12 16 7"/>
102 <line x1="21" y1="12" x2="9" y2="12"/>
103 </svg>
104 Sign out
105 </button>
106 </div>
107 </header>
42 <!-- TOP BAR -->
43 <header id="topbar">
44 <div id="breadcrumb-wrap">
45 <nav id="breadcrumb" aria-label="Breadcrumb"></nav>
46 </div>
47 <div id="topbar-actions">
48 <button id="btn-refresh" class="icon-btn" title="Refresh page" aria-label="Refresh page">
49 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
50 stroke-linecap="round" stroke-linejoin="round">
51 <polyline points="23 4 23 10 17 10" />
52 <polyline points="1 20 1 14 7 14" />
53 <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 4.36A9 9 0 0 0 20.49 15" />
54 </svg>
55 Refresh
56 </button>
108 57
109 <!-- MAIN CONTENT AREA -->
110 <main id="main-content">
111 <p id="folder-stats" class="muted hidden"></p>
58 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
59 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
60 stroke-linecap="round" stroke-linejoin="round">
61 <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
62 <polyline points="17 8 12 3 7 8" />
63 <line x1="12" y1="3" x2="12" y2="15" />
64 </svg>
65 Upload
66 </button>
67 <input id="file-input" type="file" multiple class="hidden" aria-hidden="true" />
68 <input id="folder-input" type="file" webkitdirectory directory multiple class="hidden" aria-hidden="true" />
112 69
113 <!-- Drop zone hint shown when dragging files over the main area -->
114 <div id="drop-overlay" class="hidden">
115 <span>Drop files here to upload</span>
116 </div>
70 <button id="btn-upload-folder" class="icon-btn" title="Upload folder" aria-label="Upload folder">
71 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
72 stroke-linecap="round" stroke-linejoin="round">
73 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
74 <path d="M12 11v6" />
75 <path d="M9 14h6" />
76 </svg>
77 Folder
78 </button>
79
80 <button id="btn-new-folder" class="icon-btn" title="Create new folder" aria-label="Create new folder">
81 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
82 stroke-linecap="round" stroke-linejoin="round">
83 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
84 <path d="M12 11v6" />
85 <path d="M9 14h6" />
86 </svg>
87 New Folder
88 </button>
117 89
118 <!-- File / folder grid -->
119 <div id="file-grid"></div>
90 <button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">
91 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
92 stroke-linecap="round" stroke-linejoin="round">
93 <circle cx="12" cy="8" r="4" />
94 <path d="M6 20v-2a6 6 0 0 1 12 0v2" />
95 </svg>
96 Admin
97 </button>
120 98
121 <!-- Empty directory notice -->
122 <p id="empty-notice" class="hidden muted">This folder is empty.</p>
99 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
100 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
101 stroke-linecap="round" stroke-linejoin="round">
102 <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
103 <polyline points="16 17 21 12 16 7" />
104 <line x1="21" y1="12" x2="9" y2="12" />
105 </svg>
106 Sign out
107 </button>
108 </div>
109 </header>
110
111 <!-- MAIN CONTENT AREA -->
112 <main id="main-content">
113 <p id="folder-stats" class="muted hidden"></p>
114
115 <!-- Drop zone hint shown when dragging files over the main area -->
116 <div id="drop-overlay" class="hidden">
117 <span>Drop files here to upload</span>
118 </div>
123 119
124 </main>
120 <!-- File / folder grid -->
121 <div id="file-grid"></div>
125 122
126 <!-- SIDEBAR -->
127 <aside id="sidebar" class="hidden">
128 <button id="sidebar-close" aria-label="Close sidebar">✕</button>
129 <div id="sidebar-icon"></div>
130 <h2 id="sidebar-name"></h2>
131 <dl id="sidebar-meta"></dl>
132 <div id="sidebar-actions"></div>
133 </aside>
123 <!-- Empty directory notice -->
124 <p id="empty-notice" class="hidden muted">This folder is empty.</p>
134 125
135 </div>
126 </main>
136 127
137 <!-- =====================================================================
128 <!-- SIDEBAR -->
129 <aside id="sidebar" class="hidden">
130 <button id="sidebar-close" aria-label="Close sidebar">✕</button>
131 <div id="sidebar-icon"></div>
132 <h2 id="sidebar-name"></h2>
133 <dl id="sidebar-meta"></dl>
134 <div id="sidebar-actions"></div>
135 </aside>
136
137 </div>
138
139 <!-- =====================================================================
138 140 ADMIN MODAL
139 141 ====================================================================== -->
140 <div id="admin-modal" class="modal-overlay hidden">
141 <div class="modal">
142 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
143 <h2>Admin Panel</h2>
144
145 <section>
146 <h3>Configured Paths</h3>
147 <div id="admin-paths"></div>
148 <div class="path-add-row">
149 <input id="admin-new-path" type="text" placeholder="/mnt/ssd/media" />
150 <button id="admin-add-path">Add</button>
151 </div>
152 <button id="admin-save-paths" class="primary">Save paths</button>
153 </section>
154
155 <section>
156 <h3>Users</h3>
157 <div id="admin-users-list"></div>
158 <button id="admin-new-user-btn" class="primary">+ New user</button>
159 </section>
160
161 <section>
162 <h3>Server</h3>
163 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
164 </section>
165 </div>
166 </div>
167
168 <!-- NEW / EDIT USER MODAL -->
169 <div id="user-modal" class="modal-overlay hidden">
170 <div class="modal">
171 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
172 <h2 id="user-modal-title">New User</h2>
173 <form id="user-form">
174 <label>Username<input id="user-username" type="text" required /></label>
175 <label id="user-password-label">
176 Password<input id="user-password" type="password" placeholder="Min 8 characters" />
177 </label>
178 <label class="checkbox-label">
179 <input id="user-is-admin" type="checkbox" />
180 Admin privileges
181 </label>
182 <div id="user-permissions"></div>
183 <p id="user-error" class="error hidden"></p>
184 <button type="submit" class="primary">Save</button>
185 </form>
142 <div id="admin-modal" class="modal-overlay hidden">
143 <div class="modal">
144 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
145 <h2>Admin Panel</h2>
146
147 <section>
148 <h3>Configured Paths</h3>
149 <div id="admin-paths"></div>
150 <div class="path-add-row">
151 <input id="admin-new-path" type="text" placeholder="/mnt/ssd/media" />
152 <button id="admin-add-path">Add</button>
153 </div>
154 <button id="admin-save-paths" class="primary">Save paths</button>
155 </section>
156
157 <section>
158 <h3>Users</h3>
159 <div id="admin-users-list"></div>
160 <button id="admin-new-user-btn" class="primary">+ New user</button>
161 </section>
162
163 <section>
164 <h3>Server</h3>
165 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
166 </section>
167 </div>
186 168 </div>
187 </div>
188
189 <!-- RENAME MODAL -->
190 <div id="rename-modal" class="modal-overlay hidden">
191 <div class="modal small">
192 <button class="modal-close" id="rename-modal-close" aria-label="Close">✕</button>
193 <h2>Rename</h2>
194 <form id="rename-form">
195 <label>New name<input id="rename-input" type="text" required /></label>
196 <p id="rename-error" class="error hidden"></p>
197 <button type="submit" class="primary">Rename</button>
198 </form>
169
170 <!-- NEW / EDIT USER MODAL -->
171 <div id="user-modal" class="modal-overlay hidden">
172 <div class="modal">
173 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
174 <h2 id="user-modal-title">New User</h2>
175 <form id="user-form">
176 <label>Username<input id="user-username" type="text" required /></label>
177 <label id="user-password-label">
178 Password<input id="user-password" type="password" placeholder="Min 8 characters" />
179 </label>
180 <label class="checkbox-label">
181 <input id="user-is-admin" type="checkbox" />
182 Admin privileges
183 </label>
184 <div id="user-permissions"></div>
185 <p id="user-error" class="error hidden"></p>
186 <button type="submit" class="primary">Save</button>
187 </form>
188 </div>
199 189 </div>
200 </div>
201
202 <!-- CONFIRM MODAL -->
203 <div id="confirm-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="confirm-modal-title">
204 <div class="modal small">
205 <h2 id="confirm-modal-title"></h2>
206 <p id="confirm-modal-message" class="dialog-message"></p>
207 <div class="dialog-actions">
208 <button id="confirm-modal-cancel">Cancel</button>
209 <button id="confirm-modal-ok" class="primary">OK</button>
190
191 <!-- RENAME MODAL -->
192 <div id="rename-modal" class="modal-overlay hidden">
193 <div class="modal small">
194 <button class="modal-close" id="rename-modal-close" aria-label="Close">✕</button>
195 <h2>Rename</h2>
196 <form id="rename-form">
197 <label>New name<input id="rename-input" type="text" required /></label>
198 <p id="rename-error" class="error hidden"></p>
199 <button type="submit" class="primary">Rename</button>
200 </form>
210 201 </div>
211 202 </div>
212 </div>
213
214 <!-- PROMPT MODAL -->
215 <div id="prompt-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="prompt-modal-title">
216 <div class="modal small">
217 <h2 id="prompt-modal-title"></h2>
218 <p id="prompt-modal-message" class="dialog-message"></p>
219 <form id="prompt-modal-form">
220 <label id="prompt-modal-label"><input id="prompt-modal-input" type="text" /></label>
221 <p id="prompt-modal-error" class="error hidden"></p>
203
204 <!-- CONFIRM MODAL -->
205 <div id="confirm-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
206 aria-labelledby="confirm-modal-title">
207 <div class="modal small">
208 <h2 id="confirm-modal-title"></h2>
209 <p id="confirm-modal-message" class="dialog-message"></p>
222 210 <div class="dialog-actions">
223 <button type="button" id="prompt-modal-cancel">Cancel</button>
224 <button type="submit" class="primary">OK</button>
211 <button id="confirm-modal-cancel">Cancel</button>
212 <button id="confirm-modal-ok" class="primary">OK</button>
225 213 </div>
226 </form>
214 </div>
215 </div>
216
217 <!-- PROMPT MODAL -->
218 <div id="prompt-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
219 aria-labelledby="prompt-modal-title">
220 <div class="modal small">
221 <h2 id="prompt-modal-title"></h2>
222 <p id="prompt-modal-message" class="dialog-message"></p>
223 <form id="prompt-modal-form">
224 <label id="prompt-modal-label"><input id="prompt-modal-input" type="text" /></label>
225 <p id="prompt-modal-error" class="error hidden"></p>
226 <div class="dialog-actions">
227 <button type="button" id="prompt-modal-cancel">Cancel</button>
228 <button type="submit" class="primary">OK</button>
229 </div>
230 </form>
231 </div>
227 232 </div>
228 </div>
229
230 <!-- OVERWRITE MODAL -->
231 <div id="overwrite-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="overwrite-modal-title">
232 <div class="modal small">
233 <h2 id="overwrite-modal-title">File already exists</h2>
234 <p class="dialog-message">
235 <strong id="overwrite-modal-filename"></strong> already exists in the destination folder.
236 What would you like to do?
237 </p>
238 <div class="dialog-actions dialog-actions--overwrite">
239 <button id="overwrite-modal-skip-all">Skip all</button>
240 <button id="overwrite-modal-no">Skip</button>
241 <button id="overwrite-modal-all" class="primary">Overwrite all</button>
242 <button id="overwrite-modal-yes" class="primary">Overwrite</button>
233
234 <!-- OVERWRITE MODAL -->
235 <div id="overwrite-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
236 aria-labelledby="overwrite-modal-title">
237 <div class="modal small">
238 <h2 id="overwrite-modal-title">File already exists</h2>
239 <p class="dialog-message">
240 <strong id="overwrite-modal-filename"></strong> already exists in the destination folder.
241 What would you like to do?
242 </p>
243 <div class="dialog-actions dialog-actions--overwrite">
244 <button id="overwrite-modal-skip-all">Skip all</button>
245 <button id="overwrite-modal-no">Skip</button>
246 <button id="overwrite-modal-all" class="primary">Overwrite all</button>
247 <button id="overwrite-modal-yes" class="primary">Overwrite</button>
248 </div>
243 249 </div>
244 250 </div>
245 </div>
246 251
247 <!-- TOAST -->
248 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
252 <!-- TOAST -->
253 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
249 254
250 <script src="app.js"></script>
255 <script src="app.js"></script>
251 256 </body>
252 </html>
257
258 </html>
@@ -1,252 +1,258 @@
1<!DOCTYPE html>
1<!DOCTYPE html>
2<html lang="en">
2<html lang="en">
3
3<head>
4<head>
4 <meta charset="UTF-8" />
5 <meta charset="UTF-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>File Manager</title>
7 <title>File Manager</title>
7 <link rel="stylesheet" href="style.css" />
8 <link rel="stylesheet" href="style.css" />
8</head>
9</head>
10
9<body>
11<body>
10
12
11<!-- =====================================================================
13 <!-- =====================================================================
12 LOGIN / SETUP OVERLAY
14 LOGIN / SETUP OVERLAY
13====================================================================== -->
15====================================================================== -->
14<div id="auth-overlay" class="overlay hidden">
16 <div id="auth-overlay" class="overlay hidden">
15 <div class="auth-card">
17 <div class="auth-card">
16 <h1 id="auth-title">Sign In</h1>
18 <h1 id="auth-title">Sign In</h1>
17 <p id="auth-subtitle" class="auth-subtitle hidden">
19 <p id="auth-subtitle" class="auth-subtitle hidden">
18 No accounts exist yet. Create the first admin account.
20 No accounts exist yet. Create the first admin account.
19 </p>
21 </p>
20 <form id="auth-form" autocomplete="off">
22 <form id="auth-form" autocomplete="off">
21 <label>
23 <label>
22 Username
24 Username
23 <input id="auth-username" type="text" autocomplete="off" required />
25 <input id="auth-username" type="text" autocomplete="off" required />
24 </label>
26 </label>
25 <label>
27 <label>
26 Password
28 Password
27 <input id="auth-password" type="password" autocomplete="new-password" required />
29 <input id="auth-password" type="password" autocomplete="new-password" required />
28 </label>
30 </label>
29 <p id="auth-error" class="error hidden"></p>
31 <p id="auth-error" class="error hidden"></p>
30 <button type="submit" id="auth-submit">Sign In</button>
32 <button type="submit" id="auth-submit">Sign In</button>
31 </form>
33 </form>
34 </div>
32 </div>
35 </div>
33</div>
34
36
35<!-- =====================================================================
37 <!-- =====================================================================
36 MAIN APP SHELL
38 MAIN APP SHELL
37====================================================================== -->
39====================================================================== -->
38<div id="app" class="hidden">
40 <div id="app" class="hidden">
39
41
40 <!-- TOP BAR -->
42 <!-- TOP BAR -->
41 <header id="topbar">
43 <header id="topbar">
42 <div id="breadcrumb-wrap">
44 <div id="breadcrumb-wrap">
43 <nav id="breadcrumb" aria-label="Breadcrumb"></nav>
45 <nav id="breadcrumb" aria-label="Breadcrumb"></nav>
44 </div>
46 </div>
45 <div id="topbar-actions">
47 <div id="topbar-actions">
46 <button id="btn-refresh" class="icon-btn" title="Refresh page" aria-label="Refresh page">
48 <button id="btn-refresh" class="icon-btn" title="Refresh page" aria-label="Refresh page">
47 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
49 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
48 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
50 stroke-linecap="round" stroke-linejoin="round">
49 <polyline points="23 4 23 10 17 10"/>
51 <polyline points="23 4 23 10 17 10" />
50 <polyline points="1 20 1 14 7 14"/>
52 <polyline points="1 20 1 14 7 14" />
51 <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 4.36A9 9 0 0 0 20.49 15"/>
53 <path d="M3.51 9a9 9 0 0 1 14.13-3.36L23 10M1 14l5.36 4.36A9 9 0 0 0 20.49 15" />
52 </svg>
54 </svg>
53 Refresh
55 Refresh
54 </button>
56 </button>
55
56 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
57 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
58 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
59 <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
60 <polyline points="17 8 12 3 7 8"/>
61 <line x1="12" y1="3" x2="12" y2="15"/>
62 </svg>
63 Upload
64 </button>
65 <input id="file-input" type="file" multiple class="hidden" aria-hidden="true" />
66 <input id="folder-input" type="file" webkitdirectory directory multiple class="hidden" aria-hidden="true" />
67
68 <button id="btn-upload-folder" class="icon-btn" title="Upload folder" aria-label="Upload folder">
69 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
70 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
71 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
72 <path d="M12 11v6"/>
73 <path d="M9 14h6"/>
74 </svg>
75 Folder
76 </button>
77
78 <button id="btn-new-folder" class="icon-btn" title="Create new folder" aria-label="Create new folder">
79 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
80 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
81 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
82 <path d="M12 11v6"/>
83 <path d="M9 14h6"/>
84 </svg>
85 New Folder
86 </button>
87
88 <button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">
89 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
90 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
91 <circle cx="12" cy="8" r="4"/>
92 <path d="M6 20v-2a6 6 0 0 1 12 0v2"/>
93 </svg>
94 Admin
95 </button>
96
97 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
98 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
99 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
100 <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>
101 <polyline points="16 17 21 12 16 7"/>
102 <line x1="21" y1="12" x2="9" y2="12"/>
103 </svg>
104 Sign out
105 </button>
106 </div>
107 </header>
108
57
109 <!-- MAIN CONTENT AREA -->
58 <button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
110 <main id="main-content">
59 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
111 <p id="folder-stats" class="muted hidden"></p>
60 stroke-linecap="round" stroke-linejoin="round">
61 <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
62 <polyline points="17 8 12 3 7 8" />
63 <line x1="12" y1="3" x2="12" y2="15" />
64 </svg>
65 Upload
66 </button>
67 <input id="file-input" type="file" multiple class="hidden" aria-hidden="true" />
68 <input id="folder-input" type="file" webkitdirectory directory multiple class="hidden" aria-hidden="true" />
112
69
113 <!-- Drop zone hint shown when dragging files over the main area -->
70 <button id="btn-upload-folder" class="icon-btn" title="Upload folder" aria-label="Upload folder">
114 <div id="drop-overlay" class="hidden">
71 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
115 <span>Drop files here to upload</span>
72 stroke-linecap="round" stroke-linejoin="round">
116 </div>
73 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
74 <path d="M12 11v6" />
75 <path d="M9 14h6" />
76 </svg>
77 Folder
78 </button>
79
80 <button id="btn-new-folder" class="icon-btn" title="Create new folder" aria-label="Create new folder">
81 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
82 stroke-linecap="round" stroke-linejoin="round">
83 <path d="M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
84 <path d="M12 11v6" />
85 <path d="M9 14h6" />
86 </svg>
87 New Folder
88 </button>
117
89
118 <!-- File / folder grid -->
90 <button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">
119 <div id="file-grid"></div>
91 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
92 stroke-linecap="round" stroke-linejoin="round">
93 <circle cx="12" cy="8" r="4" />
94 <path d="M6 20v-2a6 6 0 0 1 12 0v2" />
95 </svg>
96 Admin
97 </button>
120
98
121 <!-- Empty directory notice -->
99 <button id="btn-logout" class="icon-btn" title="Sign out" aria-label="Sign out">
122 <p id="empty-notice" class="hidden muted">This folder is empty.</p>
100 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
101 stroke-linecap="round" stroke-linejoin="round">
102 <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
103 <polyline points="16 17 21 12 16 7" />
104 <line x1="21" y1="12" x2="9" y2="12" />
105 </svg>
106 Sign out
107 </button>
108 </div>
109 </header>
110
111 <!-- MAIN CONTENT AREA -->
112 <main id="main-content">
113 <p id="folder-stats" class="muted hidden"></p>
114
115 <!-- Drop zone hint shown when dragging files over the main area -->
116 <div id="drop-overlay" class="hidden">
117 <span>Drop files here to upload</span>
118 </div>
123
119
124 </main>
120 <!-- File / folder grid -->
121 <div id="file-grid"></div>
125
122
126 <!-- SIDEBAR -->
123 <!-- Empty directory notice -->
127 <aside id="sidebar" class="hidden">
124 <p id="empty-notice" class="hidden muted">This folder is empty.</p>
128 <button id="sidebar-close" aria-label="Close sidebar">✕</button>
129 <div id="sidebar-icon"></div>
130 <h2 id="sidebar-name"></h2>
131 <dl id="sidebar-meta"></dl>
132 <div id="sidebar-actions"></div>
133 </aside>
134
125
135</div>
126 </main>
136
127
137<!-- =====================================================================
128 <!-- SIDEBAR -->
129 <aside id="sidebar" class="hidden">
130 <button id="sidebar-close" aria-label="Close sidebar">✕</button>
131 <div id="sidebar-icon"></div>
132 <h2 id="sidebar-name"></h2>
133 <dl id="sidebar-meta"></dl>
134 <div id="sidebar-actions"></div>
135 </aside>
136
137 </div>
138
139 <!-- =====================================================================
138 ADMIN MODAL
140 ADMIN MODAL
139====================================================================== -->
141====================================================================== -->
140<div id="admin-modal" class="modal-overlay hidden">
142 <div id="admin-modal" class="modal-overlay hidden">
141 <div class="modal">
143 <div class="modal">
142 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
144 <button class="modal-close" id="admin-modal-close" aria-label="Close admin panel">✕</button>
143 <h2>Admin Panel</h2>
145 <h2>Admin Panel</h2>
144
146
145 <section>
147 <section>
146 <h3>Configured Paths</h3>
148 <h3>Configured Paths</h3>
147 <div id="admin-paths"></div>
149 <div id="admin-paths"></div>
148 <div class="path-add-row">
150 <div class="path-add-row">
149 <input id="admin-new-path" type="text" placeholder="/mnt/ssd/media" />
151 <input id="admin-new-path" type="text" placeholder="/mnt/ssd/media" />
150 <button id="admin-add-path">Add</button>
152 <button id="admin-add-path">Add</button>
151 </div>
153 </div>
152 <button id="admin-save-paths" class="primary">Save paths</button>
154 <button id="admin-save-paths" class="primary">Save paths</button>
153 </section>
155 </section>
154
156
155 <section>
157 <section>
156 <h3>Users</h3>
158 <h3>Users</h3>
157 <div id="admin-users-list"></div>
159 <div id="admin-users-list"></div>
158 <button id="admin-new-user-btn" class="primary">+ New user</button>
160 <button id="admin-new-user-btn" class="primary">+ New user</button>
159 </section>
161 </section>
160
162
161 <section>
163 <section>
162 <h3>Server</h3>
164 <h3>Server</h3>
163 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
165 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
164 </section>
166 </section>
165 </div>
167 </div>
166</div>
167
168<!-- NEW / EDIT USER MODAL -->
169<div id="user-modal" class="modal-overlay hidden">
170 <div class="modal">
171 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
172 <h2 id="user-modal-title">New User</h2>
173 <form id="user-form">
174 <label>Username<input id="user-username" type="text" required /></label>
175 <label id="user-password-label">
176 Password<input id="user-password" type="password" placeholder="Min 8 characters" />
177 </label>
178 <label class="checkbox-label">
179 <input id="user-is-admin" type="checkbox" />
180 Admin privileges
181 </label>
182 <div id="user-permissions"></div>
183 <p id="user-error" class="error hidden"></p>
184 <button type="submit" class="primary">Save</button>
185 </form>
186 </div>
168 </div>
187</div>
169
188
170 <!-- NEW / EDIT USER MODAL -->
189<!-- RENAME MODAL -->
171 <div id="user-modal" class="modal-overlay hidden">
190<div id="rename-modal" class="modal-overlay hidden">
172 <div class="modal">
191 <div class="modal small">
173 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
192 <button class="modal-close" id="rename-modal-close" aria-label="Close">✕</button>
174 <h2 id="user-modal-title">New User</h2>
193 <h2>Rename</h2>
175 <form id="user-form">
194 <form id="rename-form">
176 <label>Username<input id="user-username" type="text" required /></label>
195 <label>New name<input id="rename-input" type="text" required /></label>
177 <label id="user-password-label">
196 <p id="rename-error" class="error hidden"></p>
178 Password<input id="user-password" type="password" placeholder="Min 8 characters" />
197 <button type="submit" class="primary">Rename</button>
179 </label>
198 </form>
180 <label class="checkbox-label">
181 <input id="user-is-admin" type="checkbox" />
182 Admin privileges
183 </label>
184 <div id="user-permissions"></div>
185 <p id="user-error" class="error hidden"></p>
186 <button type="submit" class="primary">Save</button>
187 </form>
188 </div>
199 </div>
189 </div>
200</div>
190
201
191 <!-- RENAME MODAL -->
202<!-- CONFIRM MODAL -->
192 <div id="rename-modal" class="modal-overlay hidden">
203<div id="confirm-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="confirm-modal-title">
193 <div class="modal small">
204 <div class="modal small">
194 <button class="modal-close" id="rename-modal-close" aria-label="Close">✕</button>
205 <h2 id="confirm-modal-title"></h2>
195 <h2>Rename</h2>
206 <p id="confirm-modal-message" class="dialog-message"></p>
196 <form id="rename-form">
207 <div class="dialog-actions">
197 <label>New name<input id="rename-input" type="text" required /></label>
208 <button id="confirm-modal-cancel">Cancel</button>
198 <p id="rename-error" class="error hidden"></p>
209 <button id="confirm-modal-ok" class="primary">OK</button>
199 <button type="submit" class="primary">Rename</button>
200 </form>
210 </div>
201 </div>
211 </div>
202 </div>
212</div>
203
213
204 <!-- CONFIRM MODAL -->
214<!-- PROMPT MODAL -->
205 <div id="confirm-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
215<div id="prompt-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="prompt-modal-title">
206 aria-labelledby="confirm-modal-title">
216 <div class="modal small">
207 <div class="modal small">
217 <h2 id="prompt-modal-title"></h2>
208 <h2 id="confirm-modal-title"></h2>
218 <p id="prompt-modal-message" class="dialog-message"></p>
209 <p id="confirm-modal-message" class="dialog-message"></p>
219 <form id="prompt-modal-form">
220 <label id="prompt-modal-label"><input id="prompt-modal-input" type="text" /></label>
221 <p id="prompt-modal-error" class="error hidden"></p>
222 <div class="dialog-actions">
210 <div class="dialog-actions">
223 <button type="button" id="prompt-modal-cancel">Cancel</button>
211 <button id="confirm-modal-cancel">Cancel</button>
224 <button type="submit" class="primary">OK</button>
212 <button id="confirm-modal-ok" class="primary">OK</button>
225 </div>
213 </div>
226 </form>
214 </div>
215 </div>
216
217 <!-- PROMPT MODAL -->
218 <div id="prompt-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
219 aria-labelledby="prompt-modal-title">
220 <div class="modal small">
221 <h2 id="prompt-modal-title"></h2>
222 <p id="prompt-modal-message" class="dialog-message"></p>
223 <form id="prompt-modal-form">
224 <label id="prompt-modal-label"><input id="prompt-modal-input" type="text" /></label>
225 <p id="prompt-modal-error" class="error hidden"></p>
226 <div class="dialog-actions">
227 <button type="button" id="prompt-modal-cancel">Cancel</button>
228 <button type="submit" class="primary">OK</button>
229 </div>
230 </form>
231 </div>
227 </div>
232 </div>
228</div>
233
229
234 <!-- OVERWRITE MODAL -->
230<!-- OVERWRITE MODAL -->
235 <div id="overwrite-modal" class="modal-overlay hidden" role="dialog" aria-modal="true"
231<div id="overwrite-modal" class="modal-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="overwrite-modal-title">
236 aria-labelledby="overwrite-modal-title">
232 <div class="modal small">
237 <div class="modal small">
233 <h2 id="overwrite-modal-title">File already exists</h2>
238 <h2 id="overwrite-modal-title">File already exists</h2>
234 <p class="dialog-message">
239 <p class="dialog-message">
235 <strong id="overwrite-modal-filename"></strong> already exists in the destination folder.
240 <strong id="overwrite-modal-filename"></strong> already exists in the destination folder.
236 What would you like to do?
241 What would you like to do?
237 </p>
242 </p>
238 <div class="dialog-actions dialog-actions--overwrite">
243 <div class="dialog-actions dialog-actions--overwrite">
239 <button id="overwrite-modal-skip-all">Skip all</button>
244 <button id="overwrite-modal-skip-all">Skip all</button>
240 <button id="overwrite-modal-no">Skip</button>
245 <button id="overwrite-modal-no">Skip</button>
241 <button id="overwrite-modal-all" class="primary">Overwrite all</button>
246 <button id="overwrite-modal-all" class="primary">Overwrite all</button>
242 <button id="overwrite-modal-yes" class="primary">Overwrite</button>
247 <button id="overwrite-modal-yes" class="primary">Overwrite</button>
248 </div>
243 </div>
249 </div>
244 </div>
250 </div>
245</div>
246
251
247<!-- TOAST -->
252 <!-- TOAST -->
248<div id="toast" aria-live="assertive" aria-atomic="true"></div>
253 <div id="toast" aria-live="assertive" aria-atomic="true"></div>
249
254
250<script src="app.js"></script>
255 <script src="app.js"></script>
251</body>
256</body>
252</html>
257
258</html>
scripts/generate-tests-md.js added +49 −0
@@ -0,0 +1,49 @@
1 #!/usr/bin/env node
2 /**
3 * Scans all test files and regenerates .github/tests.md from their test() names.
4 * Run via: node scripts/generate-tests-md.js
5 */
6
7 const fs = require("fs");
8 const path = require("path");
9
10 const TEST_DIR = path.join(__dirname, "../tests");
11 const OUT_FILE = path.join(__dirname, "../.github/tests.md");
12
13 const testFiles = fs.readdirSync(TEST_DIR)
14 .filter(f => f.endsWith(".test.js"))
15 .sort();
16
17 const lines = [
18 "# Test Index",
19 "",
20 "> Auto-generated by `scripts/generate-tests-md.js`. Do not edit by hand.",
21 "> Run `node scripts/generate-tests-md.js` to regenerate.",
22 "",
23 "---",
24 "",
25 ];
26
27 for (const file of testFiles)
28 {
29 const src = fs.readFileSync(path.join(TEST_DIR, file), "utf8");
30
31 // Match test("name", ...) — handles single and double quotes, multiline names
32 const re = /^describe\(["'`]([\s\S]*?)["'`]\s*,/gm;
33 const names = [];
34 let m;
35 while ((m = re.exec(src)) !== null)
36 names.push(m[1].replace(/\s+/g, " ").trim());
37
38 if (names.length === 0) continue;
39
40 lines.push(`## \`test/${file}\``);
41 for (const name of names)
42 lines.push(`- \`${name}\``);
43 lines.push("");
44 lines.push("---");
45 lines.push("");
46 }
47
48 fs.writeFileSync(OUT_FILE, lines.join("\n"));
49 console.log(`Written ${OUT_FILE} (${lines.length} lines, ${testFiles.length} files)`);
@@ -0,0 +1,49 @@
1#!/usr/bin/env node
2/**
3 * Scans all test files and regenerates .github/tests.md from their test() names.
4 * Run via: node scripts/generate-tests-md.js
5 */
6
7const fs = require("fs");
8const path = require("path");
9
10const TEST_DIR = path.join(__dirname, "../tests");
11const OUT_FILE = path.join(__dirname, "../.github/tests.md");
12
13const testFiles = fs.readdirSync(TEST_DIR)
14 .filter(f => f.endsWith(".test.js"))
15 .sort();
16
17const lines = [
18 "# Test Index",
19 "",
20 "> Auto-generated by `scripts/generate-tests-md.js`. Do not edit by hand.",
21 "> Run `node scripts/generate-tests-md.js` to regenerate.",
22 "",
23 "---",
24 "",
25];
26
27for (const file of testFiles)
28{
29 const src = fs.readFileSync(path.join(TEST_DIR, file), "utf8");
30
31 // Match test("name", ...) — handles single and double quotes, multiline names
32 const re = /^describe\(["'`]([\s\S]*?)["'`]\s*,/gm;
33 const names = [];
34 let m;
35 while ((m = re.exec(src)) !== null)
36 names.push(m[1].replace(/\s+/g, " ").trim());
37
38 if (names.length === 0) continue;
39
40 lines.push(`## \`test/${file}\``);
41 for (const name of names)
42 lines.push(`- \`${name}\``);
43 lines.push("");
44 lines.push("---");
45 lines.push("");
46}
47
48fs.writeFileSync(OUT_FILE, lines.join("\n"));
49console.log(`Written ${OUT_FILE} (${lines.length} lines, ${testFiles.length} files)`);
server/auth.js +121 −39
@@ -1,10 +1,12 @@
1 1 'use strict';
2 2
3 const jwt = require('jsonwebtoken');
3 const jwt = require('jsonwebtoken');
4 4 const crypto = require('crypto');
5 const geoip = require('geoip-lite');
5 const geoip = require('geoip-lite');
6 6 const { getDb } = require('./db');
7 7
8 const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
9
8 10 // Secret used to sign JWTs — generated fresh each server boot.
9 11 // Tokens from a previous boot are automatically invalid.
10 12 const JWT_SECRET = crypto.randomBytes(64).toString('hex');
@@ -13,7 +15,8 @@ const JWT_SECRET = crypto.randomBytes(64).toString('hex');
13 15 // Helpers
14 16 // ---------------------------------------------------------------------------
15 17
16 function getClientIp(req) {
18 function getClientIp (req)
19 {
17 20 // Respect X-Forwarded-For only if you trust a reverse proxy in front.
18 21 // For a direct Pi deployment, req.ip is sufficient.
19 22 let ip = req.ip || req.connection.remoteAddress || '';
@@ -24,17 +27,49 @@ function getClientIp(req) {
24 27 return ip;
25 28 }
26 29
27 function getRegion(ip) {
30 function getRegion (ip)
31 {
28 32 // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1)
29 33 const geo = geoip.lookup(ip);
30 34 // Private / RFC1918 addresses won't resolve — use ip itself as region.
31 35 return geo ? `${geo.country}:${geo.region}` : `local:${ip}`;
32 36 }
33 37
34 function fingerprintHash(fingerprint) {
38 function fingerprintHash (fingerprint)
39 {
35 40 return crypto.createHash('sha256').update(fingerprint || '').digest('hex');
36 41 }
37 42
43 function nowMs ()
44 {
45 return Date.now();
46 }
47
48 function createSession (username, req, fingerprint)
49 {
50 const db = getDb();
51 const ip = getClientIp(req);
52 const region = getRegion(ip);
53 const fpHash = fingerprintHash(fingerprint);
54 const createdAt = nowMs();
55 const sessionId = crypto.randomUUID();
56
57 db.prepare(`
58 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
59 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
60 `).run([sessionId, username, ip, region, fpHash, createdAt, createdAt]);
61
62 return { sessionId, ip, region, fpHash };
63 }
64
65 function revokeSession (sessionId)
66 {
67 if (!sessionId) return;
68 const db = getDb();
69 db.prepare('UPDATE auth_sessions SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL')
70 .run([nowMs(), sessionId]);
71 }
72
38 73 // ---------------------------------------------------------------------------
39 74 // Token creation
40 75 // ---------------------------------------------------------------------------
@@ -42,26 +77,20 @@ function fingerprintHash(fingerprint) {
42 77 /**
43 78 * Returns a signed JWT that expires at end of the current calendar day (UTC).
44 79 */
45 function createToken(username, req, fingerprint) {
46 const ip = getClientIp(req);
47 const region = getRegion(ip);
48 const fpHash = fingerprintHash(fingerprint);
49
50 // Expire at 23:59:59 UTC today
51 const now = new Date();
52 const endOfDay = new Date(Date.UTC(
53 now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
54 23, 59, 59,
55 ));
80 function createToken (username, req, fingerprint)
81 {
82 const session = createSession(username, req, fingerprint);
56 83
57 84 const payload = {
58 u: username,
59 ip: ip,
60 r: region,
61 fp: fpHash,
85 u: username,
86 ip: session.ip,
87 r: session.region,
88 fp: session.fpHash,
89 sid: session.sessionId,
62 90 };
63 91
64 return jwt.sign(payload, JWT_SECRET, { expiresIn: Math.floor((endOfDay - Date.now()) / 1000) });
92 // Keep JWT short-lived; server-side idle checks are the primary control.
93 return jwt.sign(payload, JWT_SECRET, { expiresIn: '12h' });
65 94 }
66 95
67 96 // ---------------------------------------------------------------------------
@@ -73,55 +102,98 @@ function createToken(username, req, fingerprint) {
73 102 * On success attaches `req.user = { username, isAdmin }`.
74 103 * On failure sends 401 with a generic "session invalid" message.
75 104 */
76 function requireAuth(req, res, next) {
105 function requireAuth (req, res, next)
106 {
77 107 const header = req.headers['authorization'] || '';
78 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
108 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
79 109
80 if (!token) {
110 if (!token)
111 {
81 112 return res.status(401).json({ error: 'Session invalid or expired.' });
82 113 }
83 114
84 115 let payload;
85 try {
116 try
117 {
86 118 payload = jwt.verify(token, JWT_SECRET);
87 } catch {
119 } catch
120 {
88 121 return res.status(401).json({ error: 'Session invalid or expired.' });
89 122 }
90 123
91 124 // Verify IP binding
92 125 const currentIp = getClientIp(req);
93 if (payload.ip !== currentIp) {
126 if (payload.ip !== currentIp)
127 {
94 128 // Intentionally identical error — do not reveal reason
95 129 return res.status(401).json({ error: 'Session invalid or expired.' });
96 130 }
97 131
98 132 // Verify region binding
99 133 const currentRegion = getRegion(currentIp);
100 if (payload.r !== currentRegion) {
134 if (payload.r !== currentRegion)
135 {
101 136 return res.status(401).json({ error: 'Session invalid or expired.' });
102 137 }
103 138
104 139 // Verify fingerprint (sent on every request as X-Fp header)
105 140 const fp = req.headers['x-fp'] || '';
106 if (payload.fp !== fingerprintHash(fp)) {
141 if (payload.fp !== fingerprintHash(fp))
142 {
143 return res.status(401).json({ error: 'Session invalid or expired.' });
144 }
145
146 if (!payload.sid)
147 {
148 return res.status(401).json({ error: 'Session invalid or expired.' });
149 }
150
151 const db = getDb();
152 const session = db.prepare(`
153 SELECT session_id, username, ip, region, fp_hash, last_seen_at, revoked_at
154 FROM auth_sessions
155 WHERE session_id = ?
156 `).get([payload.sid]);
157
158 if (!session || session.revoked_at)
159 {
160 return res.status(401).json({ error: 'Session invalid or expired.' });
161 }
162
163 if (session.username !== payload.u || session.ip !== currentIp || session.region !== currentRegion)
164 {
165 return res.status(401).json({ error: 'Session invalid or expired.' });
166 }
167
168 if (session.fp_hash !== payload.fp)
169 {
170 return res.status(401).json({ error: 'Session invalid or expired.' });
171 }
172
173 if (nowMs() - Number(session.last_seen_at || 0) > SESSION_IDLE_TIMEOUT_MS)
174 {
175 revokeSession(payload.sid);
107 176 return res.status(401).json({ error: 'Session invalid or expired.' });
108 177 }
109 178
179 db.prepare('UPDATE auth_sessions SET last_seen_at = ? WHERE session_id = ?').run([nowMs(), payload.sid]);
180
110 181 // Load user from DB
111 const db = getDb();
112 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
113 .get([payload.u]);
182 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
183 .get([payload.u]);
114 184
115 if (!user) {
185 if (!user)
186 {
116 187 return res.status(401).json({ error: 'Session invalid or expired.' });
117 188 }
118 189
119 190 req.user = {
120 id: user.id,
121 username: user.username,
122 isAdmin: user.is_admin === 1,
191 id: user.id,
192 username: user.username,
193 isAdmin: user.is_admin === 1,
123 194 permissions: JSON.parse(user.permissions || '{}'),
124 195 };
196 req.authSessionId = payload.sid;
125 197
126 198 next();
127 199 }
@@ -129,11 +201,21 @@ function requireAuth(req, res, next) {
129 201 /**
130 202 * Middleware that additionally requires admin privileges.
131 203 */
132 function requireAdmin(req, res, next) {
133 if (!req.user || !req.user.isAdmin) {
204 function requireAdmin (req, res, next)
205 {
206 if (!req.user || !req.user.isAdmin)
207 {
134 208 return res.status(403).json({ error: 'Admin access required.' });
135 209 }
136 210 next();
137 211 }
138 212
139 module.exports = { createToken, requireAuth, requireAdmin, getClientIp, getRegion };
213 module.exports = {
214 createToken,
215 requireAuth,
216 requireAdmin,
217 getClientIp,
218 getRegion,
219 revokeSession,
220 SESSION_IDLE_TIMEOUT_MS,
221 };
@@ -1,10 +1,12 @@
1'use strict';
1'use strict';
2
2
3const jwt = require('jsonwebtoken');
3const jwt = require('jsonwebtoken');
4const crypto = require('crypto');
4const crypto = require('crypto');
5const geoip = require('geoip-lite');
5const geoip = require('geoip-lite');
6const { getDb } = require('./db');
6const { getDb } = require('./db');
7
7
8const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
9
8// Secret used to sign JWTs — generated fresh each server boot.
10// Secret used to sign JWTs — generated fresh each server boot.
9// Tokens from a previous boot are automatically invalid.
11// Tokens from a previous boot are automatically invalid.
10const JWT_SECRET = crypto.randomBytes(64).toString('hex');
12const JWT_SECRET = crypto.randomBytes(64).toString('hex');
@@ -13,7 +15,8 @@ const JWT_SECRET = crypto.randomBytes(64).toString('hex');
13// Helpers
15// Helpers
14// ---------------------------------------------------------------------------
16// ---------------------------------------------------------------------------
15
17
16function getClientIp(req) {
18function getClientIp (req)
19{
17 // Respect X-Forwarded-For only if you trust a reverse proxy in front.
20 // Respect X-Forwarded-For only if you trust a reverse proxy in front.
18 // For a direct Pi deployment, req.ip is sufficient.
21 // For a direct Pi deployment, req.ip is sufficient.
19 let ip = req.ip || req.connection.remoteAddress || '';
22 let ip = req.ip || req.connection.remoteAddress || '';
@@ -24,17 +27,49 @@ function getClientIp(req) {
24 return ip;
27 return ip;
25}
28}
26
29
27function getRegion(ip) {
30function getRegion (ip)
31{
28 // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1)
32 // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1)
29 const geo = geoip.lookup(ip);
33 const geo = geoip.lookup(ip);
30 // Private / RFC1918 addresses won't resolve — use ip itself as region.
34 // Private / RFC1918 addresses won't resolve — use ip itself as region.
31 return geo ? `${geo.country}:${geo.region}` : `local:${ip}`;
35 return geo ? `${geo.country}:${geo.region}` : `local:${ip}`;
32}
36}
33
37
34function fingerprintHash(fingerprint) {
38function fingerprintHash (fingerprint)
39{
35 return crypto.createHash('sha256').update(fingerprint || '').digest('hex');
40 return crypto.createHash('sha256').update(fingerprint || '').digest('hex');
36}
41}
37
42
43function nowMs ()
44{
45 return Date.now();
46}
47
48function createSession (username, req, fingerprint)
49{
50 const db = getDb();
51 const ip = getClientIp(req);
52 const region = getRegion(ip);
53 const fpHash = fingerprintHash(fingerprint);
54 const createdAt = nowMs();
55 const sessionId = crypto.randomUUID();
56
57 db.prepare(`
58 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
59 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
60 `).run([sessionId, username, ip, region, fpHash, createdAt, createdAt]);
61
62 return { sessionId, ip, region, fpHash };
63}
64
65function revokeSession (sessionId)
66{
67 if (!sessionId) return;
68 const db = getDb();
69 db.prepare('UPDATE auth_sessions SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL')
70 .run([nowMs(), sessionId]);
71}
72
38// ---------------------------------------------------------------------------
73// ---------------------------------------------------------------------------
39// Token creation
74// Token creation
40// ---------------------------------------------------------------------------
75// ---------------------------------------------------------------------------
@@ -42,26 +77,20 @@ function fingerprintHash(fingerprint) {
42/**
77/**
43 * Returns a signed JWT that expires at end of the current calendar day (UTC).
78 * Returns a signed JWT that expires at end of the current calendar day (UTC).
44 */
79 */
45function createToken(username, req, fingerprint) {
80function createToken (username, req, fingerprint)
46 const ip = getClientIp(req);
81{
47 const region = getRegion(ip);
82 const session = createSession(username, req, fingerprint);
48 const fpHash = fingerprintHash(fingerprint);
49
50 // Expire at 23:59:59 UTC today
51 const now = new Date();
52 const endOfDay = new Date(Date.UTC(
53 now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
54 23, 59, 59,
55 ));
56
83
57 const payload = {
84 const payload = {
58 u: username,
85 u: username,
59 ip: ip,
86 ip: session.ip,
60 r: region,
87 r: session.region,
61 fp: fpHash,
88 fp: session.fpHash,
89 sid: session.sessionId,
62 };
90 };
63
91
64 return jwt.sign(payload, JWT_SECRET, { expiresIn: Math.floor((endOfDay - Date.now()) / 1000) });
92 // Keep JWT short-lived; server-side idle checks are the primary control.
93 return jwt.sign(payload, JWT_SECRET, { expiresIn: '12h' });
65}
94}
66
95
67// ---------------------------------------------------------------------------
96// ---------------------------------------------------------------------------
@@ -73,55 +102,98 @@ function createToken(username, req, fingerprint) {
73 * On success attaches `req.user = { username, isAdmin }`.
102 * On success attaches `req.user = { username, isAdmin }`.
74 * On failure sends 401 with a generic "session invalid" message.
103 * On failure sends 401 with a generic "session invalid" message.
75 */
104 */
76function requireAuth(req, res, next) {
105function requireAuth (req, res, next)
106{
77 const header = req.headers['authorization'] || '';
107 const header = req.headers['authorization'] || '';
78 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
108 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
79
109
80 if (!token) {
110 if (!token)
111 {
81 return res.status(401).json({ error: 'Session invalid or expired.' });
112 return res.status(401).json({ error: 'Session invalid or expired.' });
82 }
113 }
83
114
84 let payload;
115 let payload;
85 try {
116 try
117 {
86 payload = jwt.verify(token, JWT_SECRET);
118 payload = jwt.verify(token, JWT_SECRET);
87 } catch {
119 } catch
120 {
88 return res.status(401).json({ error: 'Session invalid or expired.' });
121 return res.status(401).json({ error: 'Session invalid or expired.' });
89 }
122 }
90
123
91 // Verify IP binding
124 // Verify IP binding
92 const currentIp = getClientIp(req);
125 const currentIp = getClientIp(req);
93 if (payload.ip !== currentIp) {
126 if (payload.ip !== currentIp)
127 {
94 // Intentionally identical error — do not reveal reason
128 // Intentionally identical error — do not reveal reason
95 return res.status(401).json({ error: 'Session invalid or expired.' });
129 return res.status(401).json({ error: 'Session invalid or expired.' });
96 }
130 }
97
131
98 // Verify region binding
132 // Verify region binding
99 const currentRegion = getRegion(currentIp);
133 const currentRegion = getRegion(currentIp);
100 if (payload.r !== currentRegion) {
134 if (payload.r !== currentRegion)
135 {
101 return res.status(401).json({ error: 'Session invalid or expired.' });
136 return res.status(401).json({ error: 'Session invalid or expired.' });
102 }
137 }
103
138
104 // Verify fingerprint (sent on every request as X-Fp header)
139 // Verify fingerprint (sent on every request as X-Fp header)
105 const fp = req.headers['x-fp'] || '';
140 const fp = req.headers['x-fp'] || '';
106 if (payload.fp !== fingerprintHash(fp)) {
141 if (payload.fp !== fingerprintHash(fp))
142 {
143 return res.status(401).json({ error: 'Session invalid or expired.' });
144 }
145
146 if (!payload.sid)
147 {
148 return res.status(401).json({ error: 'Session invalid or expired.' });
149 }
150
151 const db = getDb();
152 const session = db.prepare(`
153 SELECT session_id, username, ip, region, fp_hash, last_seen_at, revoked_at
154 FROM auth_sessions
155 WHERE session_id = ?
156 `).get([payload.sid]);
157
158 if (!session || session.revoked_at)
159 {
160 return res.status(401).json({ error: 'Session invalid or expired.' });
161 }
162
163 if (session.username !== payload.u || session.ip !== currentIp || session.region !== currentRegion)
164 {
165 return res.status(401).json({ error: 'Session invalid or expired.' });
166 }
167
168 if (session.fp_hash !== payload.fp)
169 {
170 return res.status(401).json({ error: 'Session invalid or expired.' });
171 }
172
173 if (nowMs() - Number(session.last_seen_at || 0) > SESSION_IDLE_TIMEOUT_MS)
174 {
175 revokeSession(payload.sid);
107 return res.status(401).json({ error: 'Session invalid or expired.' });
176 return res.status(401).json({ error: 'Session invalid or expired.' });
108 }
177 }
109
178
179 db.prepare('UPDATE auth_sessions SET last_seen_at = ? WHERE session_id = ?').run([nowMs(), payload.sid]);
180
110 // Load user from DB
181 // Load user from DB
111 const db = getDb();
182 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
112 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
183 .get([payload.u]);
113 .get([payload.u]);
114
184
115 if (!user) {
185 if (!user)
186 {
116 return res.status(401).json({ error: 'Session invalid or expired.' });
187 return res.status(401).json({ error: 'Session invalid or expired.' });
117 }
188 }
118
189
119 req.user = {
190 req.user = {
120 id: user.id,
191 id: user.id,
121 username: user.username,
192 username: user.username,
122 isAdmin: user.is_admin === 1,
193 isAdmin: user.is_admin === 1,
123 permissions: JSON.parse(user.permissions || '{}'),
194 permissions: JSON.parse(user.permissions || '{}'),
124 };
195 };
196 req.authSessionId = payload.sid;
125
197
126 next();
198 next();
127}
199}
@@ -129,11 +201,21 @@ function requireAuth(req, res, next) {
129/**
201/**
130 * Middleware that additionally requires admin privileges.
202 * Middleware that additionally requires admin privileges.
131 */
203 */
132function requireAdmin(req, res, next) {
204function requireAdmin (req, res, next)
133 if (!req.user || !req.user.isAdmin) {
205{
206 if (!req.user || !req.user.isAdmin)
207 {
134 return res.status(403).json({ error: 'Admin access required.' });
208 return res.status(403).json({ error: 'Admin access required.' });
135 }
209 }
136 next();
210 next();
137}
211}
138
212
139module.exports = { createToken, requireAuth, requireAdmin, getClientIp, getRegion };
213module.exports = {
214 createToken,
215 requireAuth,
216 requireAdmin,
217 getClientIp,
218 getRegion,
219 revokeSession,
220 SESSION_IDLE_TIMEOUT_MS,
221};
server/config.js +45 −15
@@ -1,23 +1,40 @@
1 1 'use strict';
2 2
3 const fs = require('fs');
3 const fs = require('fs');
4 4 const path = require('path');
5 5
6 6 const CONFIG_PATH = path.join(__dirname, '../config.json');
7 7
8 function loadConfig() {
9 try {
8 function loadConfig ()
9 {
10 try
11 {
10 12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
11 13 return JSON.parse(raw);
12 } catch {
14 } catch
15 {
13 16 const defaults = { port: 3000, paths: [] };
14 17 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
15 18 return defaults;
16 19 }
17 20 }
18 21
19 function saveConfig(config) {
20 fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
22 function saveConfig (config)
23 {
24 const dir = path.dirname(CONFIG_PATH);
25 const tmp = path.join(dir, '.config.json.tmp');
26 const payload = JSON.stringify(config, null, 2);
27
28 // Atomic replace to avoid partially-written config files.
29 fs.writeFileSync(tmp, payload, 'utf8');
30 fs.renameSync(tmp, CONFIG_PATH);
31 }
32
33 function normalizeForCompare (p)
34 {
35 const resolved = path.resolve(p);
36 // Windows paths are case-insensitive for normal filesystems.
37 return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
21 38 }
22 39
23 40 /**
@@ -26,16 +43,24 @@ function saveConfig(config) {
26 43 *
27 44 * Works on both Windows and Linux paths.
28 45 */
29 function getEffectivePaths(rawPaths) {
46 function getEffectivePaths (rawPaths)
47 {
30 48 if (!Array.isArray(rawPaths)) return [];
31 49
32 const sep = path.sep;
50 const sep = path.sep;
33 51 const normalized = rawPaths.map(p => path.resolve(p));
34 const unique = [...new Set(normalized)];
52 const unique = [...new Set(normalized)];
35 53
36 return unique.filter(p => {
54 return unique.filter(p =>
55 {
56 const cmpP = normalizeForCompare(p);
37 57 // Keep p only if no OTHER path in the list is a strict parent of p
38 return !unique.some(other => other !== p && p.startsWith(other + sep));
58 return !unique.some(other =>
59 {
60 if (other === p) return false;
61 const cmpOther = normalizeForCompare(other);
62 return cmpP.startsWith(cmpOther + sep);
63 });
39 64 });
40 65 }
41 66
@@ -43,13 +68,18 @@ function getEffectivePaths(rawPaths) {
43 68 * Checks whether `filePath` is safely inside one of the `allowedRoots`.
44 69 * Returns the matching root or null.
45 70 */
46 function getAllowedRoot(filePath, allowedRoots) {
71 function getAllowedRoot (filePath, allowedRoots)
72 {
47 73 const resolved = path.resolve(filePath);
48 const sep = path.sep;
74 const cmpResolved = normalizeForCompare(resolved);
75 const sep = path.sep;
49 76
50 for (const root of allowedRoots) {
77 for (const root of allowedRoots)
78 {
51 79 const resolvedRoot = path.resolve(root);
52 if (resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep)) {
80 const cmpRoot = normalizeForCompare(resolvedRoot);
81 if (cmpResolved === cmpRoot || cmpResolved.startsWith(cmpRoot + sep))
82 {
53 83 return resolvedRoot;
54 84 }
55 85 }
@@ -1,23 +1,40 @@
1'use strict';
1'use strict';
2
2
3const fs = require('fs');
3const fs = require('fs');
4const path = require('path');
4const path = require('path');
5
5
6const CONFIG_PATH = path.join(__dirname, '../config.json');
6const CONFIG_PATH = path.join(__dirname, '../config.json');
7
7
8function loadConfig() {
8function loadConfig ()
9 try {
9{
10 try
11 {
10 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
11 return JSON.parse(raw);
13 return JSON.parse(raw);
12 } catch {
14 } catch
15 {
13 const defaults = { port: 3000, paths: [] };
16 const defaults = { port: 3000, paths: [] };
14 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
17 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
15 return defaults;
18 return defaults;
16 }
19 }
17}
20}
18
21
19function saveConfig(config) {
22function saveConfig (config)
20 fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
23{
24 const dir = path.dirname(CONFIG_PATH);
25 const tmp = path.join(dir, '.config.json.tmp');
26 const payload = JSON.stringify(config, null, 2);
27
28 // Atomic replace to avoid partially-written config files.
29 fs.writeFileSync(tmp, payload, 'utf8');
30 fs.renameSync(tmp, CONFIG_PATH);
31}
32
33function normalizeForCompare (p)
34{
35 const resolved = path.resolve(p);
36 // Windows paths are case-insensitive for normal filesystems.
37 return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
21}
38}
22
39
23/**
40/**
@@ -26,16 +43,24 @@ function saveConfig(config) {
26 *
43 *
27 * Works on both Windows and Linux paths.
44 * Works on both Windows and Linux paths.
28 */
45 */
29function getEffectivePaths(rawPaths) {
46function getEffectivePaths (rawPaths)
47{
30 if (!Array.isArray(rawPaths)) return [];
48 if (!Array.isArray(rawPaths)) return [];
31
49
32 const sep = path.sep;
50 const sep = path.sep;
33 const normalized = rawPaths.map(p => path.resolve(p));
51 const normalized = rawPaths.map(p => path.resolve(p));
34 const unique = [...new Set(normalized)];
52 const unique = [...new Set(normalized)];
35
53
36 return unique.filter(p => {
54 return unique.filter(p =>
55 {
56 const cmpP = normalizeForCompare(p);
37 // Keep p only if no OTHER path in the list is a strict parent of p
57 // Keep p only if no OTHER path in the list is a strict parent of p
38 return !unique.some(other => other !== p && p.startsWith(other + sep));
58 return !unique.some(other =>
59 {
60 if (other === p) return false;
61 const cmpOther = normalizeForCompare(other);
62 return cmpP.startsWith(cmpOther + sep);
63 });
39 });
64 });
40}
65}
41
66
@@ -43,13 +68,18 @@ function getEffectivePaths(rawPaths) {
43 * Checks whether `filePath` is safely inside one of the `allowedRoots`.
68 * Checks whether `filePath` is safely inside one of the `allowedRoots`.
44 * Returns the matching root or null.
69 * Returns the matching root or null.
45 */
70 */
46function getAllowedRoot(filePath, allowedRoots) {
71function getAllowedRoot (filePath, allowedRoots)
72{
47 const resolved = path.resolve(filePath);
73 const resolved = path.resolve(filePath);
48 const sep = path.sep;
74 const cmpResolved = normalizeForCompare(resolved);
75 const sep = path.sep;
49
76
50 for (const root of allowedRoots) {
77 for (const root of allowedRoots)
78 {
51 const resolvedRoot = path.resolve(root);
79 const resolvedRoot = path.resolve(root);
52 if (resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep)) {
80 const cmpRoot = normalizeForCompare(resolvedRoot);
81 if (cmpResolved === cmpRoot || cmpResolved.startsWith(cmpRoot + sep))
82 {
53 return resolvedRoot;
83 return resolvedRoot;
54 }
84 }
55 }
85 }
server/db.js +26 −7
@@ -1,21 +1,24 @@
1 1 'use strict';
2 2
3 const path = require('path');
3 const path = require('path');
4 4 const { Database } = require('node-sqlite3-wasm');
5 5
6 6 const DB_PATH = path.join(__dirname, '../filemanager.db');
7 7 let db;
8 8
9 function getDb() {
10 if (!db) {
11 db = new Database(DB_PATH);
9 function getDb ()
10 {
11 if (!db)
12 {
13 db = new Database(DB_PATH);
12 14 db.exec('PRAGMA journal_mode = WAL');
13 15 db.exec('PRAGMA foreign_keys = ON');
14 16 }
15 17 return db;
16 18 }
17 19
18 function initDb() {
20 function initDb ()
21 {
19 22 const d = getDb();
20 23
21 24 d.exec(`
@@ -32,11 +35,27 @@ function initDb() {
32 35 uploader TEXT NOT NULL DEFAULT '',
33 36 downloaders TEXT NOT NULL DEFAULT '[]'
34 37 );
38
39 CREATE TABLE IF NOT EXISTS auth_sessions (
40 session_id TEXT PRIMARY KEY,
41 username TEXT NOT NULL,
42 ip TEXT NOT NULL,
43 region TEXT NOT NULL,
44 fp_hash TEXT NOT NULL,
45 created_at INTEGER NOT NULL,
46 last_seen_at INTEGER NOT NULL,
47 revoked_at INTEGER
48 );
49
50 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
51 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
35 52 `);
36 53 }
37 54
38 function closeDb() {
39 if (db) {
55 function closeDb ()
56 {
57 if (db)
58 {
40 59 db.close();
41 60 db = null;
42 61 }
@@ -1,21 +1,24 @@
1'use strict';
1'use strict';
2
2
3const path = require('path');
3const path = require('path');
4const { Database } = require('node-sqlite3-wasm');
4const { Database } = require('node-sqlite3-wasm');
5
5
6const DB_PATH = path.join(__dirname, '../filemanager.db');
6const DB_PATH = path.join(__dirname, '../filemanager.db');
7let db;
7let db;
8
8
9function getDb() {
9function getDb ()
10 if (!db) {
10{
11 db = new Database(DB_PATH);
11 if (!db)
12 {
13 db = new Database(DB_PATH);
12 db.exec('PRAGMA journal_mode = WAL');
14 db.exec('PRAGMA journal_mode = WAL');
13 db.exec('PRAGMA foreign_keys = ON');
15 db.exec('PRAGMA foreign_keys = ON');
14 }
16 }
15 return db;
17 return db;
16}
18}
17
19
18function initDb() {
20function initDb ()
21{
19 const d = getDb();
22 const d = getDb();
20
23
21 d.exec(`
24 d.exec(`
@@ -32,11 +35,27 @@ function initDb() {
32 uploader TEXT NOT NULL DEFAULT '',
35 uploader TEXT NOT NULL DEFAULT '',
33 downloaders TEXT NOT NULL DEFAULT '[]'
36 downloaders TEXT NOT NULL DEFAULT '[]'
34 );
37 );
38
39 CREATE TABLE IF NOT EXISTS auth_sessions (
40 session_id TEXT PRIMARY KEY,
41 username TEXT NOT NULL,
42 ip TEXT NOT NULL,
43 region TEXT NOT NULL,
44 fp_hash TEXT NOT NULL,
45 created_at INTEGER NOT NULL,
46 last_seen_at INTEGER NOT NULL,
47 revoked_at INTEGER
48 );
49
50 CREATE INDEX IF NOT EXISTS idx_auth_sessions_username ON auth_sessions(username);
51 CREATE INDEX IF NOT EXISTS idx_auth_sessions_last_seen ON auth_sessions(last_seen_at);
35 `);
52 `);
36}
53}
37
54
38function closeDb() {
55function closeDb ()
39 if (db) {
56{
57 if (db)
58 {
40 db.close();
59 db.close();
41 db = null;
60 db = null;
42 }
61 }
server/index.js +32 −16
@@ -1,11 +1,11 @@
1 1 'use strict';
2 2
3 3 const express = require('express');
4 const path = require('path');
5 const { initDb, closeDb } = require('./db');
6 const { ensureServerKeys } = require('./crypto');
7 const { loadConfig } = require('./config');
8 const authRoutes = require('./routes/auth');
4 const path = require('path');
5 const { initDb, closeDb } = require('./db');
6 const { ensureServerKeys } = require('./crypto');
7 const { loadConfig } = require('./config');
8 const authRoutes = require('./routes/auth');
9 9 const filesRoutes = require('./routes/files');
10 10 const adminRoutes = require('./routes/admin');
11 11
@@ -14,47 +14,63 @@ const app = express();
14 14 app.use(express.json({ limit: '50mb' }));
15 15 app.use(express.static(path.join(__dirname, '../public')));
16 16
17 app.use('/api/auth', authRoutes);
17 app.use('/api/auth', authRoutes);
18 18 app.use('/api/files', filesRoutes);
19 19 app.use('/api/admin', adminRoutes);
20 20
21 21 // SPA catch-all (only for non-API routes)
22 app.get('*', (req, res) => {
22 app.get('*', (req, res) =>
23 {
23 24 res.sendFile(path.join(__dirname, '../public/index.html'));
24 25 });
25 26
26 27 // Exposed so the shutdown route can trigger a graceful stop.
27 function shutdown(server) {
28 server.close(() => {
29 closeDb();
28 function shutdown (server)
29 {
30 if (!server || server.__isShuttingDown) return;
31 server.__isShuttingDown = true;
32
33 // Close DB first so file locks are released as early as possible.
34 closeDb();
35
36 server.close(() =>
37 {
30 38 process.exit(0);
31 39 });
40
32 41 // Force-exit after 5 s if connections don't drain in time.
33 setTimeout(() => {
34 closeDb();
42 setTimeout(() =>
43 {
35 44 process.exit(0);
36 45 }, 5000).unref();
37 46 }
38 47
39 function start() {
48 function start ()
49 {
40 50 initDb();
41 51 ensureServerKeys();
42 52
43 53 const config = loadConfig();
44 54 const port = config.port || 3000;
45 55
46 const server = app.listen(port, '0.0.0.0', () => {
56 const server = app.listen(port, '0.0.0.0', () =>
57 {
47 58 console.log(`File manager running at http://localhost:${port}`);
48 59 });
49 60
50 61 // Give the admin route access to the server handle for graceful shutdown.
51 62 app.set('server', server);
52 63 app.set('shutdown', () => shutdown(server));
64
65 process.on('SIGINT', () => shutdown(server));
66 process.on('SIGTERM', () => shutdown(server));
53 67 }
54 68
55 try {
69 try
70 {
56 71 start();
57 } catch (err) {
72 } catch (err)
73 {
58 74 console.error('Failed to start server:', err);
59 75 process.exit(1);
60 76 }
@@ -1,11 +1,11 @@
1'use strict';
1'use strict';
2
2
3const express = require('express');
3const express = require('express');
4const path = require('path');
4const path = require('path');
5const { initDb, closeDb } = require('./db');
5const { initDb, closeDb } = require('./db');
6const { ensureServerKeys } = require('./crypto');
6const { ensureServerKeys } = require('./crypto');
7const { loadConfig } = require('./config');
7const { loadConfig } = require('./config');
8const authRoutes = require('./routes/auth');
8const authRoutes = require('./routes/auth');
9const filesRoutes = require('./routes/files');
9const filesRoutes = require('./routes/files');
10const adminRoutes = require('./routes/admin');
10const adminRoutes = require('./routes/admin');
11
11
@@ -14,47 +14,63 @@ const app = express();
14app.use(express.json({ limit: '50mb' }));
14app.use(express.json({ limit: '50mb' }));
15app.use(express.static(path.join(__dirname, '../public')));
15app.use(express.static(path.join(__dirname, '../public')));
16
16
17app.use('/api/auth', authRoutes);
17app.use('/api/auth', authRoutes);
18app.use('/api/files', filesRoutes);
18app.use('/api/files', filesRoutes);
19app.use('/api/admin', adminRoutes);
19app.use('/api/admin', adminRoutes);
20
20
21// SPA catch-all (only for non-API routes)
21// SPA catch-all (only for non-API routes)
22app.get('*', (req, res) => {
22app.get('*', (req, res) =>
23{
23 res.sendFile(path.join(__dirname, '../public/index.html'));
24 res.sendFile(path.join(__dirname, '../public/index.html'));
24});
25});
25
26
26// Exposed so the shutdown route can trigger a graceful stop.
27// Exposed so the shutdown route can trigger a graceful stop.
27function shutdown(server) {
28function shutdown (server)
28 server.close(() => {
29{
29 closeDb();
30 if (!server || server.__isShuttingDown) return;
31 server.__isShuttingDown = true;
32
33 // Close DB first so file locks are released as early as possible.
34 closeDb();
35
36 server.close(() =>
37 {
30 process.exit(0);
38 process.exit(0);
31 });
39 });
40
32 // Force-exit after 5 s if connections don't drain in time.
41 // Force-exit after 5 s if connections don't drain in time.
33 setTimeout(() => {
42 setTimeout(() =>
34 closeDb();
43 {
35 process.exit(0);
44 process.exit(0);
36 }, 5000).unref();
45 }, 5000).unref();
37}
46}
38
47
39function start() {
48function start ()
49{
40 initDb();
50 initDb();
41 ensureServerKeys();
51 ensureServerKeys();
42
52
43 const config = loadConfig();
53 const config = loadConfig();
44 const port = config.port || 3000;
54 const port = config.port || 3000;
45
55
46 const server = app.listen(port, '0.0.0.0', () => {
56 const server = app.listen(port, '0.0.0.0', () =>
57 {
47 console.log(`File manager running at http://localhost:${port}`);
58 console.log(`File manager running at http://localhost:${port}`);
48 });
59 });
49
60
50 // Give the admin route access to the server handle for graceful shutdown.
61 // Give the admin route access to the server handle for graceful shutdown.
51 app.set('server', server);
62 app.set('server', server);
52 app.set('shutdown', () => shutdown(server));
63 app.set('shutdown', () => shutdown(server));
64
65 process.on('SIGINT', () => shutdown(server));
66 process.on('SIGTERM', () => shutdown(server));
53}
67}
54
68
55try {
69try
70{
56 start();
71 start();
57} catch (err) {
72} catch (err)
73{
58 console.error('Failed to start server:', err);
74 console.error('Failed to start server:', err);
59 process.exit(1);
75 process.exit(1);
60}
76}
server/routes/admin.js +64 −40
@@ -1,12 +1,12 @@
1 1 'use strict';
2 2
3 3 const express = require('express');
4 const bcrypt = require('bcrypt');
5 const path = require('path');
6 const router = express.Router();
4 const bcrypt = require('bcrypt');
5 const path = require('path');
6 const router = express.Router();
7 7
8 const { getDb } = require('../db');
9 const { requireAuth, requireAdmin } = require('../auth');
8 const { getDb } = require('../db');
9 const { requireAuth, requireAdmin } = require('../auth');
10 10 const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
11 11
12 12 const BCRYPT_ROUNDS = 12;
@@ -18,14 +18,15 @@ router.use(requireAuth, requireAdmin);
18 18 // GET /api/admin/users
19 19 // Returns all users.
20 20 // ---------------------------------------------------------------------------
21 router.get('/users', (req, res) => {
22 const db = getDb();
21 router.get('/users', (req, res) =>
22 {
23 const db = getDb();
23 24 const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all();
24 25 res.json({
25 26 users: users.map(u => ({
26 id: u.id,
27 username: u.username,
28 isAdmin: u.is_admin === 1,
27 id: u.id,
28 username: u.username,
29 isAdmin: u.is_admin === 1,
29 30 permissions: JSON.parse(u.permissions || '{}'),
30 31 })),
31 32 });
@@ -36,21 +37,23 @@ router.get('/users', (req, res) => {
36 37 // Body: { username, password, isAdmin, permissions }
37 38 // Creates a new user.
38 39 // ---------------------------------------------------------------------------
39 router.post('/users', (req, res) => {
40 router.post('/users', (req, res) =>
41 {
40 42 const { username, password, isAdmin, permissions } = req.body;
41 43
42 if (!username || !password || password.length < 8) {
44 if (!username || !password || password.length < 8)
45 {
43 46 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
44 47 }
45 48
46 const db = getDb();
47 const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]);
48 if (exists) return res.status(409).json({ error: 'Username already exists.' });
49 const db = getDb();
50 const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]);
51 if (exists) return res.status(409).json({ error: 'Username already exists.' });
49 52
50 53 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
51 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
52 [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})]
53 );
54 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
55 [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})]
56 );
54 57
55 58 res.status(201).json({ ok: true });
56 59 });
@@ -60,33 +63,39 @@ router.post('/users', (req, res) => {
60 63 // Body: { password?, isAdmin?, permissions? }
61 64 // Updates an existing user. At least one field must be present.
62 65 // ---------------------------------------------------------------------------
63 router.patch('/users/:id', (req, res) => {
64 const db = getDb();
66 router.patch('/users/:id', (req, res) =>
67 {
68 const db = getDb();
65 69 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
66 70 if (!user) return res.status(404).json({ error: 'User not found.' });
67 71
68 72 const { password, isAdmin, permissions } = req.body;
69 73
70 74 // Prevent removing the last admin
71 if (isAdmin === false || isAdmin === 0) {
75 if (isAdmin === false || isAdmin === 0)
76 {
72 77 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
73 if (adminCount <= 1 && user.is_admin === 1) {
78 if (adminCount <= 1 && user.is_admin === 1)
79 {
74 80 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
75 81 }
76 82 }
77 83
78 if (password !== undefined) {
84 if (password !== undefined)
85 {
79 86 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
80 87 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
81 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
88 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
82 89 }
83 90
84 if (isAdmin !== undefined) {
85 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
91 if (isAdmin !== undefined)
92 {
93 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
86 94 }
87 95
88 if (permissions !== undefined) {
89 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]);
96 if (permissions !== undefined)
97 {
98 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]);
90 99 }
91 100
92 101 res.json({ ok: true });
@@ -96,23 +105,27 @@ router.patch('/users/:id', (req, res) => {
96 105 // DELETE /api/admin/users/:id
97 106 // Deletes a user. Cannot delete yourself or the last admin.
98 107 // ---------------------------------------------------------------------------
99 router.delete('/users/:id', (req, res) => {
100 const db = getDb();
108 router.delete('/users/:id', (req, res) =>
109 {
110 const db = getDb();
101 111 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
102 112 if (!user) return res.status(404).json({ error: 'User not found.' });
103 113
104 if (String(user.id) === String(req.user.id)) {
114 if (String(user.id) === String(req.user.id))
115 {
105 116 return res.status(400).json({ error: 'Cannot delete your own account.' });
106 117 }
107 118
108 if (user.is_admin === 1) {
119 if (user.is_admin === 1)
120 {
109 121 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
110 if (adminCount <= 1) {
122 if (adminCount <= 1)
123 {
111 124 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
112 125 }
113 126 }
114 127
115 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
128 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
116 129 res.json({ ok: true });
117 130 });
118 131
@@ -120,7 +133,8 @@ router.delete('/users/:id', (req, res) => {
120 133 // GET /api/admin/config
121 134 // Returns the current server config (paths, port).
122 135 // ---------------------------------------------------------------------------
123 router.get('/config', (req, res) => {
136 router.get('/config', (req, res) =>
137 {
124 138 const config = loadConfig();
125 139 const effective = getEffectivePaths(config.paths || []);
126 140 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
@@ -131,19 +145,27 @@ router.get('/config', (req, res) => {
131 145 // Body: { paths: [...], port: number }
132 146 // Saves the config.
133 147 // ---------------------------------------------------------------------------
134 router.put('/config', (req, res) => {
148 router.put('/config', (req, res) =>
149 {
135 150 const { paths, port } = req.body;
136 151 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
137 152
138 153 const config = loadConfig();
139 154 config.paths = paths.map(p => p.trim()).filter(Boolean);
140 if (port !== undefined) {
155 if (port !== undefined)
156 {
141 157 const p = parseInt(port, 10);
142 158 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
143 159 config.port = p;
144 160 }
145 161
146 saveConfig(config);
162 try
163 {
164 saveConfig(config);
165 } catch (err)
166 {
167 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
168 }
147 169 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
148 170 });
149 171
@@ -151,10 +173,12 @@ router.put('/config', (req, res) => {
151 173 // POST /api/admin/shutdown
152 174 // Responds immediately then gracefully closes the server and DB.
153 175 // ---------------------------------------------------------------------------
154 router.post('/shutdown', (req, res) => {
176 router.post('/shutdown', (req, res) =>
177 {
155 178 res.json({ ok: true });
156 179 // Defer so the response is flushed before we start closing.
157 setImmediate(() => {
180 setImmediate(() =>
181 {
158 182 const fn = req.app.get('shutdown');
159 183 if (typeof fn === 'function') fn();
160 184 });
@@ -1,12 +1,12 @@
1'use strict';
1'use strict';
2
2
3const express = require('express');
3const express = require('express');
4const bcrypt = require('bcrypt');
4const bcrypt = require('bcrypt');
5const path = require('path');
5const path = require('path');
6const router = express.Router();
6const router = express.Router();
7
7
8const { getDb } = require('../db');
8const { getDb } = require('../db');
9const { requireAuth, requireAdmin } = require('../auth');
9const { requireAuth, requireAdmin } = require('../auth');
10const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
10const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
11
11
12const BCRYPT_ROUNDS = 12;
12const BCRYPT_ROUNDS = 12;
@@ -18,14 +18,15 @@ router.use(requireAuth, requireAdmin);
18// GET /api/admin/users
18// GET /api/admin/users
19// Returns all users.
19// Returns all users.
20// ---------------------------------------------------------------------------
20// ---------------------------------------------------------------------------
21router.get('/users', (req, res) => {
21router.get('/users', (req, res) =>
22 const db = getDb();
22{
23 const db = getDb();
23 const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all();
24 const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all();
24 res.json({
25 res.json({
25 users: users.map(u => ({
26 users: users.map(u => ({
26 id: u.id,
27 id: u.id,
27 username: u.username,
28 username: u.username,
28 isAdmin: u.is_admin === 1,
29 isAdmin: u.is_admin === 1,
29 permissions: JSON.parse(u.permissions || '{}'),
30 permissions: JSON.parse(u.permissions || '{}'),
30 })),
31 })),
31 });
32 });
@@ -36,21 +37,23 @@ router.get('/users', (req, res) => {
36// Body: { username, password, isAdmin, permissions }
37// Body: { username, password, isAdmin, permissions }
37// Creates a new user.
38// Creates a new user.
38// ---------------------------------------------------------------------------
39// ---------------------------------------------------------------------------
39router.post('/users', (req, res) => {
40router.post('/users', (req, res) =>
41{
40 const { username, password, isAdmin, permissions } = req.body;
42 const { username, password, isAdmin, permissions } = req.body;
41
43
42 if (!username || !password || password.length < 8) {
44 if (!username || !password || password.length < 8)
45 {
43 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
46 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
44 }
47 }
45
48
46 const db = getDb();
49 const db = getDb();
47 const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]);
50 const exists = db.prepare('SELECT id FROM users WHERE username = ?').get([username]);
48 if (exists) return res.status(409).json({ error: 'Username already exists.' });
51 if (exists) return res.status(409).json({ error: 'Username already exists.' });
49
52
50 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
53 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
51 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
54 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run(
52 [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})]
55 [username, hash, isAdmin ? 1 : 0, JSON.stringify(permissions || {})]
53 );
56 );
54
57
55 res.status(201).json({ ok: true });
58 res.status(201).json({ ok: true });
56});
59});
@@ -60,33 +63,39 @@ router.post('/users', (req, res) => {
60// Body: { password?, isAdmin?, permissions? }
63// Body: { password?, isAdmin?, permissions? }
61// Updates an existing user. At least one field must be present.
64// Updates an existing user. At least one field must be present.
62// ---------------------------------------------------------------------------
65// ---------------------------------------------------------------------------
63router.patch('/users/:id', (req, res) => {
66router.patch('/users/:id', (req, res) =>
64 const db = getDb();
67{
68 const db = getDb();
65 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
69 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
66 if (!user) return res.status(404).json({ error: 'User not found.' });
70 if (!user) return res.status(404).json({ error: 'User not found.' });
67
71
68 const { password, isAdmin, permissions } = req.body;
72 const { password, isAdmin, permissions } = req.body;
69
73
70 // Prevent removing the last admin
74 // Prevent removing the last admin
71 if (isAdmin === false || isAdmin === 0) {
75 if (isAdmin === false || isAdmin === 0)
76 {
72 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
77 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
73 if (adminCount <= 1 && user.is_admin === 1) {
78 if (adminCount <= 1 && user.is_admin === 1)
79 {
74 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
80 return res.status(400).json({ error: 'Cannot remove the last admin account.' });
75 }
81 }
76 }
82 }
77
83
78 if (password !== undefined) {
84 if (password !== undefined)
85 {
79 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
86 if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' });
80 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
87 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
81 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
88 db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]);
82 }
89 }
83
90
84 if (isAdmin !== undefined) {
91 if (isAdmin !== undefined)
85 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
92 {
93 db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]);
86 }
94 }
87
95
88 if (permissions !== undefined) {
96 if (permissions !== undefined)
89 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]);
97 {
98 db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(permissions), user.id]);
90 }
99 }
91
100
92 res.json({ ok: true });
101 res.json({ ok: true });
@@ -96,23 +105,27 @@ router.patch('/users/:id', (req, res) => {
96// DELETE /api/admin/users/:id
105// DELETE /api/admin/users/:id
97// Deletes a user. Cannot delete yourself or the last admin.
106// Deletes a user. Cannot delete yourself or the last admin.
98// ---------------------------------------------------------------------------
107// ---------------------------------------------------------------------------
99router.delete('/users/:id', (req, res) => {
108router.delete('/users/:id', (req, res) =>
100 const db = getDb();
109{
110 const db = getDb();
101 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
111 const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id);
102 if (!user) return res.status(404).json({ error: 'User not found.' });
112 if (!user) return res.status(404).json({ error: 'User not found.' });
103
113
104 if (String(user.id) === String(req.user.id)) {
114 if (String(user.id) === String(req.user.id))
115 {
105 return res.status(400).json({ error: 'Cannot delete your own account.' });
116 return res.status(400).json({ error: 'Cannot delete your own account.' });
106 }
117 }
107
118
108 if (user.is_admin === 1) {
119 if (user.is_admin === 1)
120 {
109 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
121 const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n;
110 if (adminCount <= 1) {
122 if (adminCount <= 1)
123 {
111 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
124 return res.status(400).json({ error: 'Cannot delete the last admin account.' });
112 }
125 }
113 }
126 }
114
127
115 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
128 db.prepare('DELETE FROM users WHERE id = ?').run([user.id]);
116 res.json({ ok: true });
129 res.json({ ok: true });
117});
130});
118
131
@@ -120,7 +133,8 @@ router.delete('/users/:id', (req, res) => {
120// GET /api/admin/config
133// GET /api/admin/config
121// Returns the current server config (paths, port).
134// Returns the current server config (paths, port).
122// ---------------------------------------------------------------------------
135// ---------------------------------------------------------------------------
123router.get('/config', (req, res) => {
136router.get('/config', (req, res) =>
137{
124 const config = loadConfig();
138 const config = loadConfig();
125 const effective = getEffectivePaths(config.paths || []);
139 const effective = getEffectivePaths(config.paths || []);
126 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
140 res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective });
@@ -131,19 +145,27 @@ router.get('/config', (req, res) => {
131// Body: { paths: [...], port: number }
145// Body: { paths: [...], port: number }
132// Saves the config.
146// Saves the config.
133// ---------------------------------------------------------------------------
147// ---------------------------------------------------------------------------
134router.put('/config', (req, res) => {
148router.put('/config', (req, res) =>
149{
135 const { paths, port } = req.body;
150 const { paths, port } = req.body;
136 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
151 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
137
152
138 const config = loadConfig();
153 const config = loadConfig();
139 config.paths = paths.map(p => p.trim()).filter(Boolean);
154 config.paths = paths.map(p => p.trim()).filter(Boolean);
140 if (port !== undefined) {
155 if (port !== undefined)
156 {
141 const p = parseInt(port, 10);
157 const p = parseInt(port, 10);
142 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
158 if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' });
143 config.port = p;
159 config.port = p;
144 }
160 }
145
161
146 saveConfig(config);
162 try
163 {
164 saveConfig(config);
165 } catch (err)
166 {
167 return res.status(500).json({ error: `Failed to save config: ${err.message}` });
168 }
147 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
169 res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) });
148});
170});
149
171
@@ -151,10 +173,12 @@ router.put('/config', (req, res) => {
151// POST /api/admin/shutdown
173// POST /api/admin/shutdown
152// Responds immediately then gracefully closes the server and DB.
174// Responds immediately then gracefully closes the server and DB.
153// ---------------------------------------------------------------------------
175// ---------------------------------------------------------------------------
154router.post('/shutdown', (req, res) => {
176router.post('/shutdown', (req, res) =>
177{
155 res.json({ ok: true });
178 res.json({ ok: true });
156 // Defer so the response is flushed before we start closing.
179 // Defer so the response is flushed before we start closing.
157 setImmediate(() => {
180 setImmediate(() =>
181 {
158 const fn = req.app.get('shutdown');
182 const fn = req.app.get('shutdown');
159 if (typeof fn === 'function') fn();
183 if (typeof fn === 'function') fn();
160 });
184 });
server/routes/auth.js +85 −36
@@ -1,20 +1,51 @@
1 1 'use strict';
2 2
3 3 const express = require('express');
4 const bcrypt = require('bcrypt');
5 const router = express.Router();
4 const bcrypt = require('bcrypt');
5 const router = express.Router();
6 6
7 const { getDb } = require('../db');
7 const { getDb } = require('../db');
8 8 const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto');
9 const { createToken, requireAuth } = require('../auth');
9 const { createToken, requireAuth, revokeSession } = require('../auth');
10 10
11 11 const BCRYPT_ROUNDS = 12;
12 12
13 function extractCredentials (body)
14 {
15 if (body && body.encrypted && body.encrypted.plaintext)
16 {
17 return body.encrypted.plaintext;
18 }
19
20 if (body && body.encrypted)
21 {
22 const plain = hybridDecrypt(body.encrypted);
23 return JSON.parse(plain);
24 }
25
26 if (body && typeof body.username === 'string' && typeof body.password === 'string')
27 {
28 return { username: body.username, password: body.password };
29 }
30
31 throw new Error('Invalid payload');
32 }
33
34 function makeAuthResponse (token, clientPublicKey)
35 {
36 if (clientPublicKey)
37 {
38 return { encrypted: hybridEncryptForClient(token, clientPublicKey) };
39 }
40 return { token };
41 }
42
13 43 // ---------------------------------------------------------------------------
14 44 // GET /api/auth/server-key
15 45 // Returns the server's RSA public key as JWK so the browser can import it.
16 46 // ---------------------------------------------------------------------------
17 router.get('/server-key', (req, res) => {
47 router.get('/server-key', (req, res) =>
48 {
18 49 res.json({ publicKey: getServerPublicKeyJwk() });
19 50 });
20 51
@@ -22,8 +53,9 @@ router.get('/server-key', (req, res) => {
22 53 // GET /api/auth/setup-needed
23 54 // Returns { needed: true } if no users exist yet.
24 55 // ---------------------------------------------------------------------------
25 router.get('/setup-needed', (req, res) => {
26 const db = getDb();
56 router.get('/setup-needed', (req, res) =>
57 {
58 const db = getDb();
27 59 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
28 60 res.json({ needed: count === 0 });
29 61 });
@@ -34,35 +66,38 @@ router.get('/setup-needed', (req, res) => {
34 66 // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey }
35 67 // The encrypted payload must be: { username, password }
36 68 // ---------------------------------------------------------------------------
37 router.post('/setup', (req, res) => {
38 const db = getDb();
69 router.post('/setup', (req, res) =>
70 {
71 const db = getDb();
39 72 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
40 if (count > 0) {
73 if (count > 0)
74 {
41 75 return res.status(403).json({ error: 'Setup already completed.' });
42 76 }
43 77
44 78 let credentials;
45 try {
46 const plain = hybridDecrypt(req.body.encrypted);
47 credentials = JSON.parse(plain);
48 } catch {
79 try
80 {
81 credentials = extractCredentials(req.body);
82 } catch
83 {
49 84 return res.status(400).json({ error: 'Invalid encrypted payload.' });
50 85 }
51 86
52 87 const { username, password } = credentials;
53 if (!username || !password || username.length < 1 || password.length < 8) {
88 if (!username || !password || username.length < 1 || password.length < 8)
89 {
54 90 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
55 91 }
56 92
57 93 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
58 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run(
59 [username, hash, '{}']
60 );
94 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run(
95 [username, hash, '{}']
96 );
61 97
62 98 // Issue token
63 const token = createToken(username, req, req.body.fingerprint || '');
64 const encrypted = hybridEncryptForClient(token, req.body.clientPublicKey);
65 res.json({ encrypted });
99 const token = createToken(username, req, req.body.fingerprint || '');
100 res.json(makeAuthResponse(token, req.body.clientPublicKey));
66 101 });
67 102
68 103 // ---------------------------------------------------------------------------
@@ -70,43 +105,57 @@ router.post('/setup', (req, res) => {
70 105 // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint }
71 106 // The encrypted payload must be: { username, password }
72 107 // ---------------------------------------------------------------------------
73 router.post('/login', (req, res) => {
108 router.post('/login', (req, res) =>
109 {
74 110 let credentials;
75 try {
76 const plain = hybridDecrypt(req.body.encrypted);
77 credentials = JSON.parse(plain);
78 } catch {
111 try
112 {
113 credentials = extractCredentials(req.body);
114 } catch
115 {
79 116 return res.status(400).json({ error: 'Invalid encrypted payload.' });
80 117 }
81 118
82 119 const { username, password } = credentials;
83 if (!username || !password) {
120 if (!username || !password)
121 {
84 122 return res.status(400).json({ error: 'Invalid credentials.' });
85 123 }
86 124
87 const db = getDb();
88 const user = db.prepare('SELECT * FROM users WHERE username = ?').get([username]);
125 const db = getDb();
126 const user = db.prepare('SELECT * FROM users WHERE username = ?').get([username]);
89 127
90 if (!user || !bcrypt.compareSync(password, user.password_hash)) {
128 if (!user || !bcrypt.compareSync(password, user.password_hash))
129 {
91 130 return res.status(401).json({ error: 'Invalid credentials.' });
92 131 }
93 132
94 133 const fingerprint = req.body.fingerprint || '';
95 const token = createToken(username, req, fingerprint);
96 const encrypted = hybridEncryptForClient(token, req.body.clientPublicKey);
97 res.json({ encrypted });
134 const token = createToken(username, req, fingerprint);
135 res.json(makeAuthResponse(token, req.body.clientPublicKey));
98 136 });
99 137
100 138 // ---------------------------------------------------------------------------
101 139 // GET /api/auth/me
102 140 // Returns the current user's basic info.
103 141 // ---------------------------------------------------------------------------
104 router.get('/me', requireAuth, (req, res) => {
142 router.get('/me', requireAuth, (req, res) =>
143 {
105 144 res.json({
106 username: req.user.username,
107 isAdmin: req.user.isAdmin,
145 username: req.user.username,
146 isAdmin: req.user.isAdmin,
108 147 permissions: req.user.permissions,
109 148 });
110 149 });
111 150
151 // ---------------------------------------------------------------------------
152 // POST /api/auth/logout
153 // Revokes the active authenticated session token.
154 // ---------------------------------------------------------------------------
155 router.post('/logout', requireAuth, (req, res) =>
156 {
157 revokeSession(req.authSessionId);
158 res.json({ ok: true });
159 });
160
112 161 module.exports = router;
@@ -1,20 +1,51 @@
1'use strict';
1'use strict';
2
2
3const express = require('express');
3const express = require('express');
4const bcrypt = require('bcrypt');
4const bcrypt = require('bcrypt');
5const router = express.Router();
5const router = express.Router();
6
6
7const { getDb } = require('../db');
7const { getDb } = require('../db');
8const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto');
8const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto');
9const { createToken, requireAuth } = require('../auth');
9const { createToken, requireAuth, revokeSession } = require('../auth');
10
10
11const BCRYPT_ROUNDS = 12;
11const BCRYPT_ROUNDS = 12;
12
12
13function extractCredentials (body)
14{
15 if (body && body.encrypted && body.encrypted.plaintext)
16 {
17 return body.encrypted.plaintext;
18 }
19
20 if (body && body.encrypted)
21 {
22 const plain = hybridDecrypt(body.encrypted);
23 return JSON.parse(plain);
24 }
25
26 if (body && typeof body.username === 'string' && typeof body.password === 'string')
27 {
28 return { username: body.username, password: body.password };
29 }
30
31 throw new Error('Invalid payload');
32}
33
34function makeAuthResponse (token, clientPublicKey)
35{
36 if (clientPublicKey)
37 {
38 return { encrypted: hybridEncryptForClient(token, clientPublicKey) };
39 }
40 return { token };
41}
42
13// ---------------------------------------------------------------------------
43// ---------------------------------------------------------------------------
14// GET /api/auth/server-key
44// GET /api/auth/server-key
15// Returns the server's RSA public key as JWK so the browser can import it.
45// Returns the server's RSA public key as JWK so the browser can import it.
16// ---------------------------------------------------------------------------
46// ---------------------------------------------------------------------------
17router.get('/server-key', (req, res) => {
47router.get('/server-key', (req, res) =>
48{
18 res.json({ publicKey: getServerPublicKeyJwk() });
49 res.json({ publicKey: getServerPublicKeyJwk() });
19});
50});
20
51
@@ -22,8 +53,9 @@ router.get('/server-key', (req, res) => {
22// GET /api/auth/setup-needed
53// GET /api/auth/setup-needed
23// Returns { needed: true } if no users exist yet.
54// Returns { needed: true } if no users exist yet.
24// ---------------------------------------------------------------------------
55// ---------------------------------------------------------------------------
25router.get('/setup-needed', (req, res) => {
56router.get('/setup-needed', (req, res) =>
26 const db = getDb();
57{
58 const db = getDb();
27 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
59 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
28 res.json({ needed: count === 0 });
60 res.json({ needed: count === 0 });
29});
61});
@@ -34,35 +66,38 @@ router.get('/setup-needed', (req, res) => {
34// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey }
66// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey }
35// The encrypted payload must be: { username, password }
67// The encrypted payload must be: { username, password }
36// ---------------------------------------------------------------------------
68// ---------------------------------------------------------------------------
37router.post('/setup', (req, res) => {
69router.post('/setup', (req, res) =>
38 const db = getDb();
70{
71 const db = getDb();
39 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
72 const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n;
40 if (count > 0) {
73 if (count > 0)
74 {
41 return res.status(403).json({ error: 'Setup already completed.' });
75 return res.status(403).json({ error: 'Setup already completed.' });
42 }
76 }
43
77
44 let credentials;
78 let credentials;
45 try {
79 try
46 const plain = hybridDecrypt(req.body.encrypted);
80 {
47 credentials = JSON.parse(plain);
81 credentials = extractCredentials(req.body);
48 } catch {
82 } catch
83 {
49 return res.status(400).json({ error: 'Invalid encrypted payload.' });
84 return res.status(400).json({ error: 'Invalid encrypted payload.' });
50 }
85 }
51
86
52 const { username, password } = credentials;
87 const { username, password } = credentials;
53 if (!username || !password || username.length < 1 || password.length < 8) {
88 if (!username || !password || username.length < 1 || password.length < 8)
89 {
54 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
90 return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' });
55 }
91 }
56
92
57 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
93 const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS);
58 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run(
94 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run(
59 [username, hash, '{}']
95 [username, hash, '{}']
60 );
96 );
61
97
62 // Issue token
98 // Issue token
63 const token = createToken(username, req, req.body.fingerprint || '');
99 const token = createToken(username, req, req.body.fingerprint || '');
64 const encrypted = hybridEncryptForClient(token, req.body.clientPublicKey);
100 res.json(makeAuthResponse(token, req.body.clientPublicKey));
65 res.json({ encrypted });
66});
101});
67
102
68// ---------------------------------------------------------------------------
103// ---------------------------------------------------------------------------
@@ -70,43 +105,57 @@ router.post('/setup', (req, res) => {
70// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint }
105// Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint }
71// The encrypted payload must be: { username, password }
106// The encrypted payload must be: { username, password }
72// ---------------------------------------------------------------------------
107// ---------------------------------------------------------------------------
73router.post('/login', (req, res) => {
108router.post('/login', (req, res) =>
109{
74 let credentials;
110 let credentials;
75 try {
111 try
76 const plain = hybridDecrypt(req.body.encrypted);
112 {
77 credentials = JSON.parse(plain);
113 credentials = extractCredentials(req.body);
78 } catch {
114 } catch
115 {
79 return res.status(400).json({ error: 'Invalid encrypted payload.' });
116 return res.status(400).json({ error: 'Invalid encrypted payload.' });
80 }
117 }
81
118
82 const { username, password } = credentials;
119 const { username, password } = credentials;
83 if (!username || !password) {
120 if (!username || !password)
121 {
84 return res.status(400).json({ error: 'Invalid credentials.' });
122 return res.status(400).json({ error: 'Invalid credentials.' });
85 }
123 }
86
124
87 const db = getDb();
125 const db = getDb();
88 const user = db.prepare('SELECT * FROM users WHERE username = ?').get([username]);
126 const user = db.prepare('SELECT * FROM users WHERE username = ?').get([username]);
89
127
90 if (!user || !bcrypt.compareSync(password, user.password_hash)) {
128 if (!user || !bcrypt.compareSync(password, user.password_hash))
129 {
91 return res.status(401).json({ error: 'Invalid credentials.' });
130 return res.status(401).json({ error: 'Invalid credentials.' });
92 }
131 }
93
132
94 const fingerprint = req.body.fingerprint || '';
133 const fingerprint = req.body.fingerprint || '';
95 const token = createToken(username, req, fingerprint);
134 const token = createToken(username, req, fingerprint);
96 const encrypted = hybridEncryptForClient(token, req.body.clientPublicKey);
135 res.json(makeAuthResponse(token, req.body.clientPublicKey));
97 res.json({ encrypted });
98});
136});
99
137
100// ---------------------------------------------------------------------------
138// ---------------------------------------------------------------------------
101// GET /api/auth/me
139// GET /api/auth/me
102// Returns the current user's basic info.
140// Returns the current user's basic info.
103// ---------------------------------------------------------------------------
141// ---------------------------------------------------------------------------
104router.get('/me', requireAuth, (req, res) => {
142router.get('/me', requireAuth, (req, res) =>
143{
105 res.json({
144 res.json({
106 username: req.user.username,
145 username: req.user.username,
107 isAdmin: req.user.isAdmin,
146 isAdmin: req.user.isAdmin,
108 permissions: req.user.permissions,
147 permissions: req.user.permissions,
109 });
148 });
110});
149});
111
150
151// ---------------------------------------------------------------------------
152// POST /api/auth/logout
153// Revokes the active authenticated session token.
154// ---------------------------------------------------------------------------
155router.post('/logout', requireAuth, (req, res) =>
156{
157 revokeSession(req.authSessionId);
158 res.json({ ok: true });
159});
160
112module.exports = router;
161module.exports = router;
server/routes/files.js +234 −86
@@ -1,25 +1,27 @@
1 1 'use strict';
2 2
3 const express = require('express');
4 const path = require('path');
5 const fs = require('fs');
6 const multer = require('multer');
7 const router = express.Router();
3 const express = require('express');
4 const path = require('path');
5 const fs = require('fs');
6 const multer = require('multer');
7 const router = express.Router();
8 8
9 const { getDb } = require('../db');
9 const { getDb } = require('../db');
10 10 const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11 const { requireAuth } = require('../auth');
11 const { requireAuth } = require('../auth');
12 12
13 13 // ---------------------------------------------------------------------------
14 14 // Multer storage — files are written directly to the target directory
15 15 // ---------------------------------------------------------------------------
16 16 const storage = multer.diskStorage({
17 destination(req, file, cb) {
17 destination (req, file, cb)
18 {
18 19 // The target directory is resolved in the route handler, so we stash it
19 20 // during the multer middleware call via req._uploadDir.
20 21 cb(null, req._uploadDir);
21 22 },
22 filename(req, file, cb) {
23 filename (req, file, cb)
24 {
23 25 cb(null, file.originalname);
24 26 },
25 27 });
@@ -33,20 +35,78 @@ const upload = multer({
33 35 // Helpers
34 36 // ---------------------------------------------------------------------------
35 37
36 function effectivePaths() {
38 function effectivePaths ()
39 {
37 40 return getEffectivePaths(loadConfig().paths || []);
38 41 }
39 42
43 function getFreeBytes (targetPath)
44 {
45 if (typeof fs.statfsSync !== 'function') return null;
46 try
47 {
48 const stat = fs.statfsSync(targetPath);
49 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
50 return stat.bavail * stat.bsize;
51 } catch
52 {
53 return null;
54 }
55 }
56
57 function getRecursiveSize (targetPath)
58 {
59 try
60 {
61 const stat = fs.statSync(targetPath);
62 if (!stat.isDirectory()) return stat.size;
63 } catch
64 {
65 return 0;
66 }
67
68 let total = 0;
69 let entries = [];
70 try
71 {
72 entries = fs.readdirSync(targetPath, { withFileTypes: true });
73 } catch
74 {
75 return 0;
76 }
77
78 for (const entry of entries)
79 {
80 const child = path.join(targetPath, entry.name);
81 if (entry.isDirectory())
82 {
83 total += getRecursiveSize(child);
84 continue;
85 }
86 try
87 {
88 total += fs.statSync(child).size;
89 } catch
90 {
91 // Ignore files that disappear during traversal.
92 }
93 }
94
95 return total;
96 }
97
40 98 /**
41 99 * Verify that the user has read access to the given configured-path label.
42 100 * `pathLabel` is the base-name of the effective path (shown in the UI).
43 101 */
44 function canRead(user, pathLabel) {
102 function canRead (user, pathLabel)
103 {
45 104 if (user.isAdmin) return true;
46 105 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
47 106 }
48 107
49 function canWrite(user, pathLabel) {
108 function canWrite (user, pathLabel)
109 {
50 110 if (user.isAdmin) return true;
51 111 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
52 112 }
@@ -55,7 +115,8 @@ function canWrite(user, pathLabel) {
55 115 * Given an absolute path and the effective-paths list, return
56 116 * { root, label } where label is the base-name of the root, or null.
57 117 */
58 function resolveRoot(absPath, roots) {
118 function resolveRoot (absPath, roots)
119 {
59 120 const matchedRoot = getAllowedRoot(absPath, roots);
60 121 if (!matchedRoot) return null;
61 122 return { root: matchedRoot, label: path.basename(matchedRoot) };
@@ -65,7 +126,8 @@ function resolveRoot(absPath, roots) {
65 126 // GET /api/files/roots
66 127 // Returns the effective configured paths the user can read.
67 128 // ---------------------------------------------------------------------------
68 router.get('/roots', requireAuth, (req, res) => {
129 router.get('/roots', requireAuth, (req, res) =>
130 {
69 131 const roots = effectivePaths();
70 132 const readable = roots
71 133 .filter(r => canRead(req.user, path.basename(r)))
@@ -77,38 +139,43 @@ router.get('/roots', requireAuth, (req, res) => {
77 139 // GET /api/files/list?dir=<absolute-path>
78 140 // Lists files and folders in the given directory.
79 141 // ---------------------------------------------------------------------------
80 router.get('/list', requireAuth, (req, res) => {
81 const dir = req.query.dir;
142 router.get('/list', requireAuth, (req, res) =>
143 {
144 const dir = req.query.dir;
82 145 if (!dir) return res.status(400).json({ error: 'dir is required.' });
83 146
84 147 const roots = effectivePaths();
85 const info = resolveRoot(dir, roots);
86 if (!info) return res.status(403).json({ error: 'Access denied.' });
148 const info = resolveRoot(dir, roots);
149 if (!info) return res.status(403).json({ error: 'Access denied.' });
87 150 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
88 151
89 152 let entries;
90 try {
153 try
154 {
91 155 entries = fs.readdirSync(dir, { withFileTypes: true });
92 } catch {
156 } catch
157 {
93 158 return res.status(404).json({ error: 'Directory not found.' });
94 159 }
95 160
96 const items = entries.map(e => {
161 const items = entries.map(e =>
162 {
97 163 const fullPath = path.join(dir, e.name);
98 164 let size = null;
99 165 let mtime = null;
100 try {
166 try
167 {
101 168 const stat = fs.statSync(fullPath);
102 size = stat.size;
169 size = stat.size;
103 170 mtime = stat.mtime.toISOString();
104 171 } catch { /* ignore */ }
105 172
106 173 return {
107 name: e.name,
108 isDir: e.isDirectory(),
174 name: e.name,
175 isDir: e.isDirectory(),
109 176 size,
110 177 mtime,
111 path: fullPath,
178 path: fullPath,
112 179 };
113 180 });
114 181
@@ -119,66 +186,107 @@ router.get('/list', requireAuth, (req, res) => {
119 186 // GET /api/files/meta?file=<absolute-path>
120 187 // Returns file metadata from the DB.
121 188 // ---------------------------------------------------------------------------
122 router.get('/meta', requireAuth, (req, res) => {
123 const file = req.query.file;
189 router.get('/meta', requireAuth, (req, res) =>
190 {
191 const file = req.query.file;
124 192 if (!file) return res.status(400).json({ error: 'file is required.' });
125 193
126 194 const roots = effectivePaths();
127 const info = resolveRoot(file, roots);
128 if (!info || !canRead(req.user, info.label)) {
195 const info = resolveRoot(file, roots);
196 if (!info || !canRead(req.user, info.label))
197 {
129 198 return res.status(403).json({ error: 'Access denied.' });
130 199 }
131 200
132 201 let stat;
133 try {
202 try
203 {
134 204 stat = fs.statSync(file);
135 } catch {
205 } catch
206 {
136 207 return res.status(404).json({ error: 'File not found.' });
137 208 }
138 209
139 const db = getDb();
210 const db = getDb();
140 211 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
141 212
142 213 res.json({
143 name: path.basename(file),
144 size: stat.size,
145 mtime: stat.mtime.toISOString(),
146 uploader: meta ? meta.uploader : '',
214 name: path.basename(file),
215 size: stat.size,
216 mtime: stat.mtime.toISOString(),
217 uploader: meta ? meta.uploader : '',
147 218 downloaders: meta ? JSON.parse(meta.downloaders) : [],
148 219 });
149 220 });
150 221
222 // ---------------------------------------------------------------------------
223 // GET /api/files/space?dir=<absolute-path>
224 // Returns recursive used bytes for dir and available bytes on its root fs.
225 // ---------------------------------------------------------------------------
226 router.get('/space', requireAuth, (req, res) =>
227 {
228 const dir = req.query.dir;
229 if (!dir) return res.status(400).json({ error: 'dir is required.' });
230
231 const roots = effectivePaths();
232 const info = resolveRoot(dir, roots);
233 if (!info || !canRead(req.user, info.label))
234 {
235 return res.status(403).json({ error: 'Access denied.' });
236 }
237
238 if (!fs.existsSync(dir))
239 {
240 return res.status(404).json({ error: 'Path not found.' });
241 }
242
243 const usedBytes = getRecursiveSize(dir);
244 const freeBytes = getFreeBytes(info.root);
245 res.json({
246 usedBytes,
247 freeBytes,
248 rootPath: info.root,
249 rootLabel: info.label,
250 });
251 });
252
151 253 // ---------------------------------------------------------------------------
152 254 // GET /api/files/download?file=<absolute-path>
153 255 // Streams the file to the client; records the download.
154 256 // ---------------------------------------------------------------------------
155 router.get('/download', requireAuth, (req, res) => {
156 const file = req.query.file;
257 router.get('/download', requireAuth, (req, res) =>
258 {
259 const file = req.query.file;
157 260 if (!file) return res.status(400).json({ error: 'file is required.' });
158 261
159 262 const roots = effectivePaths();
160 const info = resolveRoot(file, roots);
161 if (!info || !canRead(req.user, info.label)) {
263 const info = resolveRoot(file, roots);
264 if (!info || !canRead(req.user, info.label))
265 {
162 266 return res.status(403).json({ error: 'Access denied.' });
163 267 }
164 268
165 if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
269 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
270 {
166 271 return res.status(404).json({ error: 'File not found.' });
167 272 }
168 273
169 274 // Record download
170 const db = getDb();
171 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
172 if (meta) {
275 const db = getDb();
276 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
277 if (meta)
278 {
173 279 const downloaders = JSON.parse(meta.downloaders);
174 if (!downloaders.includes(req.user.username)) {
280 if (!downloaders.includes(req.user.username))
281 {
175 282 downloaders.push(req.user.username);
176 283 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
177 .run([JSON.stringify(downloaders), file]);
284 .run([JSON.stringify(downloaders), file]);
178 285 }
179 } else {
286 } else
287 {
180 288 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
181 .run([file, '', JSON.stringify([req.user.username])]);
289 .run([file, '', JSON.stringify([req.user.username])]);
182 290 }
183 291
184 292 res.download(file, path.basename(file));
@@ -188,35 +296,56 @@ router.get('/download', requireAuth, (req, res) => {
188 296 // POST /api/files/upload?dir=<absolute-path>
189 297 // Accepts multipart file upload.
190 298 // ---------------------------------------------------------------------------
191 router.post('/upload', requireAuth, (req, res, next) => {
192 const dir = req.query.dir;
299 router.post('/upload', requireAuth, (req, res, next) =>
300 {
301 const dir = req.query.dir;
193 302 if (!dir) return res.status(400).json({ error: 'dir is required.' });
194 303
195 304 const roots = effectivePaths();
196 const info = resolveRoot(dir, roots);
197 if (!info || !canWrite(req.user, info.label)) {
305 const info = resolveRoot(dir, roots);
306 if (!info || !canWrite(req.user, info.label))
307 {
198 308 return res.status(403).json({ error: 'Access denied.' });
199 309 }
200 310
201 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
311 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
312 {
202 313 return res.status(404).json({ error: 'Directory not found.' });
203 314 }
204 315
316 const announcedSize = Number(req.header('x-upload-size') || 0);
317 if (Number.isFinite(announcedSize) && announcedSize > 0)
318 {
319 const freeBytes = getFreeBytes(info.root);
320 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
321 {
322 return res.status(413).json({
323 error: 'Upload too large for remaining free space on selected root.',
324 freeBytes,
325 requiredBytes: announcedSize,
326 });
327 }
328 }
329
205 330 req._uploadDir = dir;
206 331
207 upload.array('files')(req, res, (err) => {
332 upload.array('files')(req, res, (err) =>
333 {
208 334 if (err) return res.status(500).json({ error: err.message });
209 335
210 336 const db = getDb();
211 for (const f of (req.files || [])) {
337 for (const f of (req.files || []))
338 {
212 339 const filePath = path.join(dir, f.originalname);
213 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
214 if (existing) {
340 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
341 if (existing)
342 {
215 343 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
216 .run([req.user.username, filePath]);
217 } else {
344 .run([req.user.username, filePath]);
345 } else
346 {
218 347 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
219 .run([filePath, req.user.username, '[]']);
348 .run([filePath, req.user.username, '[]']);
220 349 }
221 350 }
222 351 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
@@ -227,37 +356,43 @@ router.post('/upload', requireAuth, (req, res, next) => {
227 356 // POST /api/files/rename
228 357 // Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
229 358 // ---------------------------------------------------------------------------
230 router.post('/rename', requireAuth, (req, res) => {
359 router.post('/rename', requireAuth, (req, res) =>
360 {
231 361 const { from, to } = req.body;
232 362 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
233 363
234 364 // Prevent path traversal in the new name
235 if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) {
365 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
366 {
236 367 return res.status(400).json({ error: 'Invalid name.' });
237 368 }
238 369
239 370 const roots = effectivePaths();
240 const info = resolveRoot(from, roots);
241 if (!info || !canWrite(req.user, info.label)) {
371 const info = resolveRoot(from, roots);
372 if (!info || !canWrite(req.user, info.label))
373 {
242 374 return res.status(403).json({ error: 'Access denied.' });
243 375 }
244 376
245 377 const dest = path.join(path.dirname(from), to);
246 378
247 379 // Ensure dest is still inside the same root
248 if (!getAllowedRoot(dest, roots)) {
380 if (!getAllowedRoot(dest, roots))
381 {
249 382 return res.status(403).json({ error: 'Access denied.' });
250 383 }
251 384
252 try {
385 try
386 {
253 387 fs.renameSync(from, dest);
254 } catch (err) {
388 } catch (err)
389 {
255 390 return res.status(500).json({ error: err.message });
256 391 }
257 392
258 393 // Update DB meta key
259 394 const db = getDb();
260 db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
395 db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
261 396
262 397 res.json({ ok: true });
263 398 });
@@ -266,28 +401,34 @@ router.post('/rename', requireAuth, (req, res) => {
266 401 // POST /api/files/mkdir
267 402 // Body: { dir: <absolute-path>, name: <folder-name> }
268 403 // ---------------------------------------------------------------------------
269 router.post('/mkdir', requireAuth, (req, res) => {
404 router.post('/mkdir', requireAuth, (req, res) =>
405 {
270 406 const { dir, name } = req.body;
271 407 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
272 408
273 if (path.basename(name) !== name) {
409 if (path.basename(name) !== name)
410 {
274 411 return res.status(400).json({ error: 'Invalid folder name.' });
275 412 }
276 413
277 414 const roots = effectivePaths();
278 const info = resolveRoot(dir, roots);
279 if (!info || !canWrite(req.user, info.label)) {
415 const info = resolveRoot(dir, roots);
416 if (!info || !canWrite(req.user, info.label))
417 {
280 418 return res.status(403).json({ error: 'Access denied.' });
281 419 }
282 420
283 421 const newDir = path.join(dir, name);
284 if (!getAllowedRoot(newDir, roots)) {
422 if (!getAllowedRoot(newDir, roots))
423 {
285 424 return res.status(403).json({ error: 'Access denied.' });
286 425 }
287 426
288 try {
427 try
428 {
289 429 fs.mkdirSync(newDir, { recursive: false });
290 } catch (err) {
430 } catch (err)
431 {
291 432 return res.status(500).json({ error: err.message });
292 433 }
293 434
@@ -298,36 +439,43 @@ router.post('/mkdir', requireAuth, (req, res) => {
298 439 // POST /api/files/delete
299 440 // Body: { path: <absolute-path> }
300 441 // ---------------------------------------------------------------------------
301 router.post('/delete', requireAuth, (req, res) => {
442 router.post('/delete', requireAuth, (req, res) =>
443 {
302 444 const target = req.body.path;
303 445 if (!target) return res.status(400).json({ error: 'path is required.' });
304 446
305 447 const roots = effectivePaths();
306 const info = resolveRoot(target, roots);
307 if (!info || !canWrite(req.user, info.label)) {
448 const info = resolveRoot(target, roots);
449 if (!info || !canWrite(req.user, info.label))
450 {
308 451 return res.status(403).json({ error: 'Access denied.' });
309 452 }
310 453
311 454 // Do not allow deleting a configured root itself
312 if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) {
455 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
456 {
313 457 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
314 458 }
315 459
316 try {
460 try
461 {
317 462 const stat = fs.statSync(target);
318 if (stat.isDirectory()) {
463 if (stat.isDirectory())
464 {
319 465 fs.rmSync(target, { recursive: true, force: true });
320 } else {
466 } else
467 {
321 468 fs.unlinkSync(target);
322 469 }
323 } catch (err) {
470 } catch (err)
471 {
324 472 return res.status(500).json({ error: err.message });
325 473 }
326 474
327 475 // Clean up any DB meta entries under that path
328 476 const db = getDb();
329 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
330 .run([target, target + path.sep + '%']);
477 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
478 .run([target, target + path.sep + '%']);
331 479
332 480 res.json({ ok: true });
333 481 });
@@ -1,25 +1,27 @@
1'use strict';
1'use strict';
2
2
3const express = require('express');
3const express = require('express');
4const path = require('path');
4const path = require('path');
5const fs = require('fs');
5const fs = require('fs');
6const multer = require('multer');
6const 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, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
11const { requireAuth } = require('../auth');
12
12
13// ---------------------------------------------------------------------------
13// ---------------------------------------------------------------------------
14// Multer storage — files are written directly to the target directory
14// Multer storage — files are written directly to the target directory
15// ---------------------------------------------------------------------------
15// ---------------------------------------------------------------------------
16const storage = multer.diskStorage({
16const storage = multer.diskStorage({
17 destination(req, file, cb) {
17 destination (req, file, cb)
18 {
18 // The target directory is resolved in the route handler, so we stash it
19 // The target directory is resolved in the route handler, so we stash it
19 // during the multer middleware call via req._uploadDir.
20 // during the multer middleware call via req._uploadDir.
20 cb(null, req._uploadDir);
21 cb(null, req._uploadDir);
21 },
22 },
22 filename(req, file, cb) {
23 filename (req, file, cb)
24 {
23 cb(null, file.originalname);
25 cb(null, file.originalname);
24 },
26 },
25});
27});
@@ -33,20 +35,78 @@ const upload = multer({
33// Helpers
35// Helpers
34// ---------------------------------------------------------------------------
36// ---------------------------------------------------------------------------
35
37
36function effectivePaths() {
38function effectivePaths ()
39{
37 return getEffectivePaths(loadConfig().paths || []);
40 return getEffectivePaths(loadConfig().paths || []);
38}
41}
39
42
43function getFreeBytes (targetPath)
44{
45 if (typeof fs.statfsSync !== 'function') return null;
46 try
47 {
48 const stat = fs.statfsSync(targetPath);
49 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
50 return stat.bavail * stat.bsize;
51 } catch
52 {
53 return null;
54 }
55}
56
57function getRecursiveSize (targetPath)
58{
59 try
60 {
61 const stat = fs.statSync(targetPath);
62 if (!stat.isDirectory()) return stat.size;
63 } catch
64 {
65 return 0;
66 }
67
68 let total = 0;
69 let entries = [];
70 try
71 {
72 entries = fs.readdirSync(targetPath, { withFileTypes: true });
73 } catch
74 {
75 return 0;
76 }
77
78 for (const entry of entries)
79 {
80 const child = path.join(targetPath, entry.name);
81 if (entry.isDirectory())
82 {
83 total += getRecursiveSize(child);
84 continue;
85 }
86 try
87 {
88 total += fs.statSync(child).size;
89 } catch
90 {
91 // Ignore files that disappear during traversal.
92 }
93 }
94
95 return total;
96}
97
40/**
98/**
41 * Verify that the user has read access to the given configured-path label.
99 * Verify that the user has read access to the given configured-path label.
42 * `pathLabel` is the base-name of the effective path (shown in the UI).
100 * `pathLabel` is the base-name of the effective path (shown in the UI).
43 */
101 */
44function canRead(user, pathLabel) {
102function canRead (user, pathLabel)
103{
45 if (user.isAdmin) return true;
104 if (user.isAdmin) return true;
46 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
105 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
47}
106}
48
107
49function canWrite(user, pathLabel) {
108function canWrite (user, pathLabel)
109{
50 if (user.isAdmin) return true;
110 if (user.isAdmin) return true;
51 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
111 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
52}
112}
@@ -55,7 +115,8 @@ function canWrite(user, pathLabel) {
55 * Given an absolute path and the effective-paths list, return
115 * Given an absolute path and the effective-paths list, return
56 * { root, label } where label is the base-name of the root, or null.
116 * { root, label } where label is the base-name of the root, or null.
57 */
117 */
58function resolveRoot(absPath, roots) {
118function resolveRoot (absPath, roots)
119{
59 const matchedRoot = getAllowedRoot(absPath, roots);
120 const matchedRoot = getAllowedRoot(absPath, roots);
60 if (!matchedRoot) return null;
121 if (!matchedRoot) return null;
61 return { root: matchedRoot, label: path.basename(matchedRoot) };
122 return { root: matchedRoot, label: path.basename(matchedRoot) };
@@ -65,7 +126,8 @@ function resolveRoot(absPath, roots) {
65// GET /api/files/roots
126// GET /api/files/roots
66// Returns the effective configured paths the user can read.
127// Returns the effective configured paths the user can read.
67// ---------------------------------------------------------------------------
128// ---------------------------------------------------------------------------
68router.get('/roots', requireAuth, (req, res) => {
129router.get('/roots', requireAuth, (req, res) =>
130{
69 const roots = effectivePaths();
131 const roots = effectivePaths();
70 const readable = roots
132 const readable = roots
71 .filter(r => canRead(req.user, path.basename(r)))
133 .filter(r => canRead(req.user, path.basename(r)))
@@ -77,38 +139,43 @@ router.get('/roots', requireAuth, (req, res) => {
77// GET /api/files/list?dir=<absolute-path>
139// GET /api/files/list?dir=<absolute-path>
78// Lists files and folders in the given directory.
140// Lists files and folders in the given directory.
79// ---------------------------------------------------------------------------
141// ---------------------------------------------------------------------------
80router.get('/list', requireAuth, (req, res) => {
142router.get('/list', requireAuth, (req, res) =>
81 const dir = req.query.dir;
143{
144 const dir = req.query.dir;
82 if (!dir) return res.status(400).json({ error: 'dir is required.' });
145 if (!dir) return res.status(400).json({ error: 'dir is required.' });
83
146
84 const roots = effectivePaths();
147 const roots = effectivePaths();
85 const info = resolveRoot(dir, roots);
148 const info = resolveRoot(dir, roots);
86 if (!info) return res.status(403).json({ error: 'Access denied.' });
149 if (!info) return res.status(403).json({ error: 'Access denied.' });
87 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
150 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
88
151
89 let entries;
152 let entries;
90 try {
153 try
154 {
91 entries = fs.readdirSync(dir, { withFileTypes: true });
155 entries = fs.readdirSync(dir, { withFileTypes: true });
92 } catch {
156 } catch
157 {
93 return res.status(404).json({ error: 'Directory not found.' });
158 return res.status(404).json({ error: 'Directory not found.' });
94 }
159 }
95
160
96 const items = entries.map(e => {
161 const items = entries.map(e =>
162 {
97 const fullPath = path.join(dir, e.name);
163 const fullPath = path.join(dir, e.name);
98 let size = null;
164 let size = null;
99 let mtime = null;
165 let mtime = null;
100 try {
166 try
167 {
101 const stat = fs.statSync(fullPath);
168 const stat = fs.statSync(fullPath);
102 size = stat.size;
169 size = stat.size;
103 mtime = stat.mtime.toISOString();
170 mtime = stat.mtime.toISOString();
104 } catch { /* ignore */ }
171 } catch { /* ignore */ }
105
172
106 return {
173 return {
107 name: e.name,
174 name: e.name,
108 isDir: e.isDirectory(),
175 isDir: e.isDirectory(),
109 size,
176 size,
110 mtime,
177 mtime,
111 path: fullPath,
178 path: fullPath,
112 };
179 };
113 });
180 });
114
181
@@ -119,66 +186,107 @@ router.get('/list', requireAuth, (req, res) => {
119// GET /api/files/meta?file=<absolute-path>
186// GET /api/files/meta?file=<absolute-path>
120// Returns file metadata from the DB.
187// Returns file metadata from the DB.
121// ---------------------------------------------------------------------------
188// ---------------------------------------------------------------------------
122router.get('/meta', requireAuth, (req, res) => {
189router.get('/meta', requireAuth, (req, res) =>
123 const file = req.query.file;
190{
191 const file = req.query.file;
124 if (!file) return res.status(400).json({ error: 'file is required.' });
192 if (!file) return res.status(400).json({ error: 'file is required.' });
125
193
126 const roots = effectivePaths();
194 const roots = effectivePaths();
127 const info = resolveRoot(file, roots);
195 const info = resolveRoot(file, roots);
128 if (!info || !canRead(req.user, info.label)) {
196 if (!info || !canRead(req.user, info.label))
197 {
129 return res.status(403).json({ error: 'Access denied.' });
198 return res.status(403).json({ error: 'Access denied.' });
130 }
199 }
131
200
132 let stat;
201 let stat;
133 try {
202 try
203 {
134 stat = fs.statSync(file);
204 stat = fs.statSync(file);
135 } catch {
205 } catch
206 {
136 return res.status(404).json({ error: 'File not found.' });
207 return res.status(404).json({ error: 'File not found.' });
137 }
208 }
138
209
139 const db = getDb();
210 const db = getDb();
140 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
211 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
141
212
142 res.json({
213 res.json({
143 name: path.basename(file),
214 name: path.basename(file),
144 size: stat.size,
215 size: stat.size,
145 mtime: stat.mtime.toISOString(),
216 mtime: stat.mtime.toISOString(),
146 uploader: meta ? meta.uploader : '',
217 uploader: meta ? meta.uploader : '',
147 downloaders: meta ? JSON.parse(meta.downloaders) : [],
218 downloaders: meta ? JSON.parse(meta.downloaders) : [],
148 });
219 });
149});
220});
150
221
222// ---------------------------------------------------------------------------
223// GET /api/files/space?dir=<absolute-path>
224// Returns recursive used bytes for dir and available bytes on its root fs.
225// ---------------------------------------------------------------------------
226router.get('/space', requireAuth, (req, res) =>
227{
228 const dir = req.query.dir;
229 if (!dir) return res.status(400).json({ error: 'dir is required.' });
230
231 const roots = effectivePaths();
232 const info = resolveRoot(dir, roots);
233 if (!info || !canRead(req.user, info.label))
234 {
235 return res.status(403).json({ error: 'Access denied.' });
236 }
237
238 if (!fs.existsSync(dir))
239 {
240 return res.status(404).json({ error: 'Path not found.' });
241 }
242
243 const usedBytes = getRecursiveSize(dir);
244 const freeBytes = getFreeBytes(info.root);
245 res.json({
246 usedBytes,
247 freeBytes,
248 rootPath: info.root,
249 rootLabel: info.label,
250 });
251});
252
151// ---------------------------------------------------------------------------
253// ---------------------------------------------------------------------------
152// GET /api/files/download?file=<absolute-path>
254// GET /api/files/download?file=<absolute-path>
153// Streams the file to the client; records the download.
255// Streams the file to the client; records the download.
154// ---------------------------------------------------------------------------
256// ---------------------------------------------------------------------------
155router.get('/download', requireAuth, (req, res) => {
257router.get('/download', requireAuth, (req, res) =>
156 const file = req.query.file;
258{
259 const file = req.query.file;
157 if (!file) return res.status(400).json({ error: 'file is required.' });
260 if (!file) return res.status(400).json({ error: 'file is required.' });
158
261
159 const roots = effectivePaths();
262 const roots = effectivePaths();
160 const info = resolveRoot(file, roots);
263 const info = resolveRoot(file, roots);
161 if (!info || !canRead(req.user, info.label)) {
264 if (!info || !canRead(req.user, info.label))
265 {
162 return res.status(403).json({ error: 'Access denied.' });
266 return res.status(403).json({ error: 'Access denied.' });
163 }
267 }
164
268
165 if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) {
269 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
270 {
166 return res.status(404).json({ error: 'File not found.' });
271 return res.status(404).json({ error: 'File not found.' });
167 }
272 }
168
273
169 // Record download
274 // Record download
170 const db = getDb();
275 const db = getDb();
171 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
276 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
172 if (meta) {
277 if (meta)
278 {
173 const downloaders = JSON.parse(meta.downloaders);
279 const downloaders = JSON.parse(meta.downloaders);
174 if (!downloaders.includes(req.user.username)) {
280 if (!downloaders.includes(req.user.username))
281 {
175 downloaders.push(req.user.username);
282 downloaders.push(req.user.username);
176 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
283 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
177 .run([JSON.stringify(downloaders), file]);
284 .run([JSON.stringify(downloaders), file]);
178 }
285 }
179 } else {
286 } else
287 {
180 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
288 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
181 .run([file, '', JSON.stringify([req.user.username])]);
289 .run([file, '', JSON.stringify([req.user.username])]);
182 }
290 }
183
291
184 res.download(file, path.basename(file));
292 res.download(file, path.basename(file));
@@ -188,35 +296,56 @@ router.get('/download', requireAuth, (req, res) => {
188// POST /api/files/upload?dir=<absolute-path>
296// POST /api/files/upload?dir=<absolute-path>
189// Accepts multipart file upload.
297// Accepts multipart file upload.
190// ---------------------------------------------------------------------------
298// ---------------------------------------------------------------------------
191router.post('/upload', requireAuth, (req, res, next) => {
299router.post('/upload', requireAuth, (req, res, next) =>
192 const dir = req.query.dir;
300{
301 const dir = req.query.dir;
193 if (!dir) return res.status(400).json({ error: 'dir is required.' });
302 if (!dir) return res.status(400).json({ error: 'dir is required.' });
194
303
195 const roots = effectivePaths();
304 const roots = effectivePaths();
196 const info = resolveRoot(dir, roots);
305 const info = resolveRoot(dir, roots);
197 if (!info || !canWrite(req.user, info.label)) {
306 if (!info || !canWrite(req.user, info.label))
307 {
198 return res.status(403).json({ error: 'Access denied.' });
308 return res.status(403).json({ error: 'Access denied.' });
199 }
309 }
200
310
201 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
311 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
312 {
202 return res.status(404).json({ error: 'Directory not found.' });
313 return res.status(404).json({ error: 'Directory not found.' });
203 }
314 }
204
315
316 const announcedSize = Number(req.header('x-upload-size') || 0);
317 if (Number.isFinite(announcedSize) && announcedSize > 0)
318 {
319 const freeBytes = getFreeBytes(info.root);
320 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
321 {
322 return res.status(413).json({
323 error: 'Upload too large for remaining free space on selected root.',
324 freeBytes,
325 requiredBytes: announcedSize,
326 });
327 }
328 }
329
205 req._uploadDir = dir;
330 req._uploadDir = dir;
206
331
207 upload.array('files')(req, res, (err) => {
332 upload.array('files')(req, res, (err) =>
333 {
208 if (err) return res.status(500).json({ error: err.message });
334 if (err) return res.status(500).json({ error: err.message });
209
335
210 const db = getDb();
336 const db = getDb();
211 for (const f of (req.files || [])) {
337 for (const f of (req.files || []))
338 {
212 const filePath = path.join(dir, f.originalname);
339 const filePath = path.join(dir, f.originalname);
213 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
340 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
214 if (existing) {
341 if (existing)
342 {
215 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
343 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
216 .run([req.user.username, filePath]);
344 .run([req.user.username, filePath]);
217 } else {
345 } else
346 {
218 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
347 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
219 .run([filePath, req.user.username, '[]']);
348 .run([filePath, req.user.username, '[]']);
220 }
349 }
221 }
350 }
222 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
351 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
@@ -227,37 +356,43 @@ router.post('/upload', requireAuth, (req, res, next) => {
227// POST /api/files/rename
356// POST /api/files/rename
228// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
357// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
229// ---------------------------------------------------------------------------
358// ---------------------------------------------------------------------------
230router.post('/rename', requireAuth, (req, res) => {
359router.post('/rename', requireAuth, (req, res) =>
360{
231 const { from, to } = req.body;
361 const { from, to } = req.body;
232 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
362 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
233
363
234 // Prevent path traversal in the new name
364 // Prevent path traversal in the new name
235 if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) {
365 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
366 {
236 return res.status(400).json({ error: 'Invalid name.' });
367 return res.status(400).json({ error: 'Invalid name.' });
237 }
368 }
238
369
239 const roots = effectivePaths();
370 const roots = effectivePaths();
240 const info = resolveRoot(from, roots);
371 const info = resolveRoot(from, roots);
241 if (!info || !canWrite(req.user, info.label)) {
372 if (!info || !canWrite(req.user, info.label))
373 {
242 return res.status(403).json({ error: 'Access denied.' });
374 return res.status(403).json({ error: 'Access denied.' });
243 }
375 }
244
376
245 const dest = path.join(path.dirname(from), to);
377 const dest = path.join(path.dirname(from), to);
246
378
247 // Ensure dest is still inside the same root
379 // Ensure dest is still inside the same root
248 if (!getAllowedRoot(dest, roots)) {
380 if (!getAllowedRoot(dest, roots))
381 {
249 return res.status(403).json({ error: 'Access denied.' });
382 return res.status(403).json({ error: 'Access denied.' });
250 }
383 }
251
384
252 try {
385 try
386 {
253 fs.renameSync(from, dest);
387 fs.renameSync(from, dest);
254 } catch (err) {
388 } catch (err)
389 {
255 return res.status(500).json({ error: err.message });
390 return res.status(500).json({ error: err.message });
256 }
391 }
257
392
258 // Update DB meta key
393 // Update DB meta key
259 const db = getDb();
394 const db = getDb();
260 db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
395 db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]);
261
396
262 res.json({ ok: true });
397 res.json({ ok: true });
263});
398});
@@ -266,28 +401,34 @@ router.post('/rename', requireAuth, (req, res) => {
266// POST /api/files/mkdir
401// POST /api/files/mkdir
267// Body: { dir: <absolute-path>, name: <folder-name> }
402// Body: { dir: <absolute-path>, name: <folder-name> }
268// ---------------------------------------------------------------------------
403// ---------------------------------------------------------------------------
269router.post('/mkdir', requireAuth, (req, res) => {
404router.post('/mkdir', requireAuth, (req, res) =>
405{
270 const { dir, name } = req.body;
406 const { dir, name } = req.body;
271 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
407 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
272
408
273 if (path.basename(name) !== name) {
409 if (path.basename(name) !== name)
410 {
274 return res.status(400).json({ error: 'Invalid folder name.' });
411 return res.status(400).json({ error: 'Invalid folder name.' });
275 }
412 }
276
413
277 const roots = effectivePaths();
414 const roots = effectivePaths();
278 const info = resolveRoot(dir, roots);
415 const info = resolveRoot(dir, roots);
279 if (!info || !canWrite(req.user, info.label)) {
416 if (!info || !canWrite(req.user, info.label))
417 {
280 return res.status(403).json({ error: 'Access denied.' });
418 return res.status(403).json({ error: 'Access denied.' });
281 }
419 }
282
420
283 const newDir = path.join(dir, name);
421 const newDir = path.join(dir, name);
284 if (!getAllowedRoot(newDir, roots)) {
422 if (!getAllowedRoot(newDir, roots))
423 {
285 return res.status(403).json({ error: 'Access denied.' });
424 return res.status(403).json({ error: 'Access denied.' });
286 }
425 }
287
426
288 try {
427 try
428 {
289 fs.mkdirSync(newDir, { recursive: false });
429 fs.mkdirSync(newDir, { recursive: false });
290 } catch (err) {
430 } catch (err)
431 {
291 return res.status(500).json({ error: err.message });
432 return res.status(500).json({ error: err.message });
292 }
433 }
293
434
@@ -298,36 +439,43 @@ router.post('/mkdir', requireAuth, (req, res) => {
298// POST /api/files/delete
439// POST /api/files/delete
299// Body: { path: <absolute-path> }
440// Body: { path: <absolute-path> }
300// ---------------------------------------------------------------------------
441// ---------------------------------------------------------------------------
301router.post('/delete', requireAuth, (req, res) => {
442router.post('/delete', requireAuth, (req, res) =>
443{
302 const target = req.body.path;
444 const target = req.body.path;
303 if (!target) return res.status(400).json({ error: 'path is required.' });
445 if (!target) return res.status(400).json({ error: 'path is required.' });
304
446
305 const roots = effectivePaths();
447 const roots = effectivePaths();
306 const info = resolveRoot(target, roots);
448 const info = resolveRoot(target, roots);
307 if (!info || !canWrite(req.user, info.label)) {
449 if (!info || !canWrite(req.user, info.label))
450 {
308 return res.status(403).json({ error: 'Access denied.' });
451 return res.status(403).json({ error: 'Access denied.' });
309 }
452 }
310
453
311 // Do not allow deleting a configured root itself
454 // Do not allow deleting a configured root itself
312 if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) {
455 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
456 {
313 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
457 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
314 }
458 }
315
459
316 try {
460 try
461 {
317 const stat = fs.statSync(target);
462 const stat = fs.statSync(target);
318 if (stat.isDirectory()) {
463 if (stat.isDirectory())
464 {
319 fs.rmSync(target, { recursive: true, force: true });
465 fs.rmSync(target, { recursive: true, force: true });
320 } else {
466 } else
467 {
321 fs.unlinkSync(target);
468 fs.unlinkSync(target);
322 }
469 }
323 } catch (err) {
470 } catch (err)
471 {
324 return res.status(500).json({ error: err.message });
472 return res.status(500).json({ error: err.message });
325 }
473 }
326
474
327 // Clean up any DB meta entries under that path
475 // Clean up any DB meta entries under that path
328 const db = getDb();
476 const db = getDb();
329 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
477 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
330 .run([target, target + path.sep + '%']);
478 .run([target, target + path.sep + '%']);
331
479
332 res.json({ ok: true });
480 res.json({ ok: true });
333});
481});
start.sh +3 −0
@@ -8,6 +8,9 @@ set -euo pipefail
8 8 SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9 9 cd "$SCRIPT_DIR"
10 10
11 echo "Clearing old database lock if needed"
12 rm filemanager.db.lock
13
11 14 echo "[start.sh] git reset --hard"
12 15 git reset --hard
13 16
@@ -8,6 +8,9 @@ set -euo pipefail
8SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
8SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9cd "$SCRIPT_DIR"
9cd "$SCRIPT_DIR"
10
10
11echo "Clearing old database lock if needed"
12rm filemanager.db.lock
13
11echo "[start.sh] git reset --hard"
14echo "[start.sh] git reset --hard"
12git reset --hard
15git reset --hard
13
16
tests/auth.routes.test.js +172 −55
@@ -5,17 +5,20 @@
5 5 * Spins up an in-memory Express app with a fresh in-memory SQLite database.
6 6 */
7 7
8 const express = require('express');
9 const { once } = require('events');
10 const http = require('http');
11 const crypto = require('crypto');
8 const express = require('express');
9 const { once } = require('events');
10 const http = require('http');
11 const crypto = require('crypto');
12 12
13 13 // ── patch DB to use in-memory database before requiring routes ──────────────
14 jest.mock('../server/db', () => {
14 jest.mock('../server/db', () =>
15 {
15 16 const { Database } = require('node-sqlite3-wasm');
16 17 let db;
17 function getDb() {
18 if (!db) {
18 function getDb ()
19 {
20 if (!db)
21 {
19 22 db = new Database(':memory:');
20 23 db.exec(`
21 24 CREATE TABLE IF NOT EXISTS users (
@@ -30,15 +33,26 @@ jest.mock('../server/db', () => {
30 33 uploader TEXT NOT NULL DEFAULT '',
31 34 downloaders TEXT NOT NULL DEFAULT '[]'
32 35 );
36 CREATE TABLE IF NOT EXISTS auth_sessions (
37 session_id TEXT PRIMARY KEY,
38 username TEXT NOT NULL,
39 ip TEXT NOT NULL,
40 region TEXT NOT NULL,
41 fp_hash TEXT NOT NULL,
42 created_at INTEGER NOT NULL,
43 last_seen_at INTEGER NOT NULL,
44 revoked_at INTEGER
45 );
33 46 `);
34 47 }
35 48 return db;
36 49 }
37 function initDb() { getDb(); }
50 function initDb () { getDb(); }
38 51 return { getDb, initDb };
39 52 });
40 53
41 54 const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
55 const { SESSION_IDLE_TIMEOUT_MS } = require('../server/auth');
42 56 const authRoutes = require('../server/routes/auth');
43 57
44 58 jest.setTimeout(30000);
@@ -48,15 +62,17 @@ jest.setTimeout(30000);
48 62 let server;
49 63 let baseUrl;
50 64
51 beforeAll(async () => {
65 beforeAll(async () =>
66 {
52 67 ensureServerKeys();
53 68 const app = express();
54 69 app.use(express.json());
55 app.use('/api/auth', authRoutes);
56 app.use((err, req, res, next) => {
57 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
58 });
59 server = http.createServer(app);
70 app.use('/api/auth', authRoutes);
71 app.use((err, req, res, next) =>
72 {
73 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
74 });
75 server = http.createServer(app);
60 76 server.listen(0);
61 77 await once(server, 'listening');
62 78 const port = server.address().port;
@@ -67,9 +83,12 @@ afterAll(() => server.close());
67 83
68 84 // ── helpers ────────────────────────────────────────────────────────────────
69 85
70 function get(path) {
71 return new Promise((resolve, reject) => {
72 http.get(baseUrl + path, res => {
86 function get (path)
87 {
88 return new Promise((resolve, reject) =>
89 {
90 http.get(baseUrl + path, res =>
91 {
73 92 let body = '';
74 93 res.on('data', d => body += d);
75 94 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
@@ -77,13 +96,16 @@ function get(path) {
77 96 });
78 97 }
79 98
80 function post(path, data) {
99 function post (path, data)
100 {
81 101 const payload = JSON.stringify(data);
82 return new Promise((resolve, reject) => {
102 return new Promise((resolve, reject) =>
103 {
83 104 const req = http.request(baseUrl + path, {
84 method: 'POST',
105 method: 'POST',
85 106 headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
86 }, res => {
107 }, res =>
108 {
87 109 let body = '';
88 110 res.on('data', d => body += d);
89 111 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
@@ -94,33 +116,60 @@ function post(path, data) {
94 116 });
95 117 }
96 118
119 function authed (method, path, token, fingerprint, data)
120 {
121 const payload = data ? JSON.stringify(data) : undefined;
122 return new Promise((resolve, reject) =>
123 {
124 const req = http.request(baseUrl + path, {
125 method,
126 headers: {
127 Authorization: `Bearer ${token}`,
128 'X-Fp': fingerprint,
129 'Content-Type': 'application/json',
130 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
131 },
132 }, res =>
133 {
134 let body = '';
135 res.on('data', d => body += d);
136 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
137 });
138 req.on('error', reject);
139 if (payload) req.write(payload);
140 req.end();
141 });
142 }
143
97 144 /** Simulate the client-side hybrid encrypt targeting the server public key. */
98 function clientEncrypt(obj) {
99 const jwk = getServerPublicKeyJwk();
145 function clientEncrypt (obj)
146 {
147 const jwk = getServerPublicKeyJwk();
100 148 const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
101 const plain = JSON.stringify(obj);
149 const plain = JSON.stringify(obj);
102 150 const aesKey = crypto.randomBytes(32);
103 const iv = crypto.randomBytes(12);
151 const iv = crypto.randomBytes(12);
104 152 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
105 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
106 const tag = cipher.getAuthTag();
107 const ek = crypto.publicEncrypt(
153 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
154 const tag = cipher.getAuthTag();
155 const ek = crypto.publicEncrypt(
108 156 { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
109 157 aesKey,
110 158 );
111 159 return {
112 160 encryptedKey: ek.toString('base64'),
113 iv: iv.toString('base64'),
114 ciphertext: ct.toString('base64'),
115 tag: tag.toString('base64'),
161 iv: iv.toString('base64'),
162 ciphertext: ct.toString('base64'),
163 tag: tag.toString('base64'),
116 164 };
117 165 }
118 166
119 167 /** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */
120 function makeClientKeyPair() {
168 function makeClientKeyPair ()
169 {
121 170 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
122 171 modulusLength: 2048,
123 publicKeyEncoding: { type: 'spki', format: 'pem' },
172 publicKeyEncoding: { type: 'spki', format: 'pem' },
124 173 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
125 174 });
126 175 const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
@@ -128,12 +177,13 @@ function makeClientKeyPair() {
128 177 }
129 178
130 179 /** Decrypt the token the server sends back. */
131 function clientDecrypt(payload, privateKey) {
180 function clientDecrypt (payload, privateKey)
181 {
132 182 const ek = Buffer.from(payload.encryptedKey, 'base64');
133 const iv = Buffer.from(payload.iv, 'base64');
134 const ct = Buffer.from(payload.ciphertext, 'base64');
135 const tg = Buffer.from(payload.tag, 'base64');
136 const rawAes = crypto.privateDecrypt(
183 const iv = Buffer.from(payload.iv, 'base64');
184 const ct = Buffer.from(payload.ciphertext, 'base64');
185 const tg = Buffer.from(payload.tag, 'base64');
186 const rawAes = crypto.privateDecrypt(
137 187 { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
138 188 ek,
139 189 );
@@ -144,28 +194,34 @@ function clientDecrypt(payload, privateKey) {
144 194
145 195 // ── tests ──────────────────────────────────────────────────────────────────
146 196
147 describe('GET /api/auth/server-key', () => {
148 test('returns a JWK public key', async () => {
197 describe('GET /api/auth/server-key', () =>
198 {
199 test('returns a JWK public key', async () =>
200 {
149 201 const { status, body } = await get('/api/auth/server-key');
150 202 expect(status).toBe(200);
151 203 expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) });
152 204 });
153 205 });
154 206
155 describe('GET /api/auth/setup-needed', () => {
156 test('returns needed=true when no users exist', async () => {
207 describe('GET /api/auth/setup-needed', () =>
208 {
209 test('returns needed=true when no users exist', async () =>
210 {
157 211 const { status, body } = await get('/api/auth/setup-needed');
158 212 expect(status).toBe(200);
159 213 expect(body.needed).toBe(true);
160 214 });
161 215 });
162 216
163 describe('POST /api/auth/setup', () => {
217 describe('POST /api/auth/setup', () =>
218 {
164 219 let kp;
165 220
166 221 beforeAll(() => { kp = makeClientKeyPair(); });
167 222
168 test('rejects weak password', async () => {
223 test('rejects weak password', async () =>
224 {
169 225 const encrypted = clientEncrypt({ username: 'admin', password: 'short' });
170 226 const { status, body } = await post('/api/auth/setup', {
171 227 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -173,7 +229,8 @@ describe('POST /api/auth/setup', () => {
173 229 expect(status).toBe(400);
174 230 });
175 231
176 test('creates admin and returns encrypted token', async () => {
232 test('creates admin and returns encrypted token', async () =>
233 {
177 234 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
178 235 const { status, body } = await post('/api/auth/setup', {
179 236 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -181,9 +238,9 @@ describe('POST /api/auth/setup', () => {
181 238 expect(status).toBe(200);
182 239 expect(body.encrypted).toMatchObject({
183 240 encryptedKey: expect.any(String),
184 iv: expect.any(String),
185 ciphertext: expect.any(String),
186 tag: expect.any(String),
241 iv: expect.any(String),
242 ciphertext: expect.any(String),
243 tag: expect.any(String),
187 244 });
188 245
189 246 // Token should be a valid JWT string
@@ -191,13 +248,15 @@ describe('POST /api/auth/setup', () => {
191 248 expect(token.split('.').length).toBe(3);
192 249 });
193 250
194 test('setup-needed is now false', async () => {
251 test('setup-needed is now false', async () =>
252 {
195 253 const { body } = await get('/api/auth/setup-needed');
196 254 expect(body.needed).toBe(false);
197 255 });
198 256
199 test('cannot run setup again once a user exists', async () => {
200 const kp2 = makeClientKeyPair();
257 test('cannot run setup again once a user exists', async () =>
258 {
259 const kp2 = makeClientKeyPair();
201 260 const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' });
202 261 const { status } = await post('/api/auth/setup', {
203 262 encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test',
@@ -206,11 +265,13 @@ describe('POST /api/auth/setup', () => {
206 265 });
207 266 });
208 267
209 describe('POST /api/auth/login', () => {
268 describe('POST /api/auth/login', () =>
269 {
210 270 let kp;
211 271 beforeAll(() => { kp = makeClientKeyPair(); });
212 272
213 test('rejects wrong password', async () => {
273 test('rejects wrong password', async () =>
274 {
214 275 const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' });
215 276 const { status } = await post('/api/auth/login', {
216 277 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -218,7 +279,8 @@ describe('POST /api/auth/login', () => {
218 279 expect(status).toBe(401);
219 280 });
220 281
221 test('returns encrypted token on correct credentials', async () => {
282 test('returns encrypted token on correct credentials', async () =>
283 {
222 284 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
223 285 const { status, body } = await post('/api/auth/login', {
224 286 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -228,7 +290,8 @@ describe('POST /api/auth/login', () => {
228 290 expect(token.split('.').length).toBe(3);
229 291 });
230 292
231 test('rejects invalid encrypted payload', async () => {
293 test('rejects invalid encrypted payload', async () =>
294 {
232 295 const { status } = await post('/api/auth/login', {
233 296 encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' },
234 297 clientPublicKey: kp.publicKeyJwk,
@@ -237,3 +300,57 @@ describe('POST /api/auth/login', () => {
237 300 expect(status).toBe(400);
238 301 });
239 302 });
303
304 describe('session lifecycle', () =>
305 {
306 const fingerprint = 'test';
307
308 async function loginAndGetToken ()
309 {
310 const kp = makeClientKeyPair();
311 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
312 const { status, body } = await post('/api/auth/login', {
313 encrypted,
314 clientPublicKey: kp.publicKeyJwk,
315 fingerprint,
316 });
317 expect(status).toBe(200);
318 return clientDecrypt(body.encrypted, kp.privateKey);
319 }
320
321 test('POST /api/auth/logout revokes active session', async () =>
322 {
323 const token = await loginAndGetToken();
324
325 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
326 expect(meBefore.status).toBe(200);
327
328 const logout = await authed('POST', '/api/auth/logout', token, fingerprint, {});
329 expect(logout.status).toBe(200);
330 expect(logout.body.ok).toBe(true);
331
332 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
333 expect(meAfter.status).toBe(401);
334 });
335
336 test('session expires after 1 hour of inactivity', async () =>
337 {
338 const token = await loginAndGetToken();
339
340 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
341 expect(meBefore.status).toBe(200);
342
343 const realNow = Date.now;
344 try
345 {
346 const jumped = realNow() + SESSION_IDLE_TIMEOUT_MS + 1000;
347 Date.now = jest.fn(() => jumped);
348
349 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
350 expect(meAfter.status).toBe(401);
351 } finally
352 {
353 Date.now = realNow;
354 }
355 });
356 });
@@ -5,17 +5,20 @@
5 * Spins up an in-memory Express app with a fresh in-memory SQLite database.
5 * Spins up an in-memory Express app with a fresh in-memory SQLite database.
6 */
6 */
7
7
8const express = require('express');
8const express = require('express');
9const { once } = require('events');
9const { once } = require('events');
10const http = require('http');
10const http = require('http');
11const crypto = require('crypto');
11const crypto = require('crypto');
12
12
13// ── patch DB to use in-memory database before requiring routes ──────────────
13// ── patch DB to use in-memory database before requiring routes ──────────────
14jest.mock('../server/db', () => {
14jest.mock('../server/db', () =>
15{
15 const { Database } = require('node-sqlite3-wasm');
16 const { Database } = require('node-sqlite3-wasm');
16 let db;
17 let db;
17 function getDb() {
18 function getDb ()
18 if (!db) {
19 {
20 if (!db)
21 {
19 db = new Database(':memory:');
22 db = new Database(':memory:');
20 db.exec(`
23 db.exec(`
21 CREATE TABLE IF NOT EXISTS users (
24 CREATE TABLE IF NOT EXISTS users (
@@ -30,15 +33,26 @@ jest.mock('../server/db', () => {
30 uploader TEXT NOT NULL DEFAULT '',
33 uploader TEXT NOT NULL DEFAULT '',
31 downloaders TEXT NOT NULL DEFAULT '[]'
34 downloaders TEXT NOT NULL DEFAULT '[]'
32 );
35 );
36 CREATE TABLE IF NOT EXISTS auth_sessions (
37 session_id TEXT PRIMARY KEY,
38 username TEXT NOT NULL,
39 ip TEXT NOT NULL,
40 region TEXT NOT NULL,
41 fp_hash TEXT NOT NULL,
42 created_at INTEGER NOT NULL,
43 last_seen_at INTEGER NOT NULL,
44 revoked_at INTEGER
45 );
33 `);
46 `);
34 }
47 }
35 return db;
48 return db;
36 }
49 }
37 function initDb() { getDb(); }
50 function initDb () { getDb(); }
38 return { getDb, initDb };
51 return { getDb, initDb };
39});
52});
40
53
41const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
54const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
55const { SESSION_IDLE_TIMEOUT_MS } = require('../server/auth');
42const authRoutes = require('../server/routes/auth');
56const authRoutes = require('../server/routes/auth');
43
57
44jest.setTimeout(30000);
58jest.setTimeout(30000);
@@ -48,15 +62,17 @@ jest.setTimeout(30000);
48let server;
62let server;
49let baseUrl;
63let baseUrl;
50
64
51beforeAll(async () => {
65beforeAll(async () =>
66{
52 ensureServerKeys();
67 ensureServerKeys();
53 const app = express();
68 const app = express();
54 app.use(express.json());
69 app.use(express.json());
55 app.use('/api/auth', authRoutes);
70 app.use('/api/auth', authRoutes);
56 app.use((err, req, res, next) => {
71 app.use((err, req, res, next) =>
57 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
72 {
58 });
73 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
59 server = http.createServer(app);
74 });
75 server = http.createServer(app);
60 server.listen(0);
76 server.listen(0);
61 await once(server, 'listening');
77 await once(server, 'listening');
62 const port = server.address().port;
78 const port = server.address().port;
@@ -67,9 +83,12 @@ afterAll(() => server.close());
67
83
68// ── helpers ────────────────────────────────────────────────────────────────
84// ── helpers ────────────────────────────────────────────────────────────────
69
85
70function get(path) {
86function get (path)
71 return new Promise((resolve, reject) => {
87{
72 http.get(baseUrl + path, res => {
88 return new Promise((resolve, reject) =>
89 {
90 http.get(baseUrl + path, res =>
91 {
73 let body = '';
92 let body = '';
74 res.on('data', d => body += d);
93 res.on('data', d => body += d);
75 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
94 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
@@ -77,13 +96,16 @@ function get(path) {
77 });
96 });
78}
97}
79
98
80function post(path, data) {
99function post (path, data)
100{
81 const payload = JSON.stringify(data);
101 const payload = JSON.stringify(data);
82 return new Promise((resolve, reject) => {
102 return new Promise((resolve, reject) =>
103 {
83 const req = http.request(baseUrl + path, {
104 const req = http.request(baseUrl + path, {
84 method: 'POST',
105 method: 'POST',
85 headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
106 headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
86 }, res => {
107 }, res =>
108 {
87 let body = '';
109 let body = '';
88 res.on('data', d => body += d);
110 res.on('data', d => body += d);
89 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
111 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
@@ -94,33 +116,60 @@ function post(path, data) {
94 });
116 });
95}
117}
96
118
119function authed (method, path, token, fingerprint, data)
120{
121 const payload = data ? JSON.stringify(data) : undefined;
122 return new Promise((resolve, reject) =>
123 {
124 const req = http.request(baseUrl + path, {
125 method,
126 headers: {
127 Authorization: `Bearer ${token}`,
128 'X-Fp': fingerprint,
129 'Content-Type': 'application/json',
130 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
131 },
132 }, res =>
133 {
134 let body = '';
135 res.on('data', d => body += d);
136 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
137 });
138 req.on('error', reject);
139 if (payload) req.write(payload);
140 req.end();
141 });
142}
143
97/** Simulate the client-side hybrid encrypt targeting the server public key. */
144/** Simulate the client-side hybrid encrypt targeting the server public key. */
98function clientEncrypt(obj) {
145function clientEncrypt (obj)
99 const jwk = getServerPublicKeyJwk();
146{
147 const jwk = getServerPublicKeyJwk();
100 const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
148 const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
101 const plain = JSON.stringify(obj);
149 const plain = JSON.stringify(obj);
102 const aesKey = crypto.randomBytes(32);
150 const aesKey = crypto.randomBytes(32);
103 const iv = crypto.randomBytes(12);
151 const iv = crypto.randomBytes(12);
104 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
152 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
105 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
153 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
106 const tag = cipher.getAuthTag();
154 const tag = cipher.getAuthTag();
107 const ek = crypto.publicEncrypt(
155 const ek = crypto.publicEncrypt(
108 { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
156 { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
109 aesKey,
157 aesKey,
110 );
158 );
111 return {
159 return {
112 encryptedKey: ek.toString('base64'),
160 encryptedKey: ek.toString('base64'),
113 iv: iv.toString('base64'),
161 iv: iv.toString('base64'),
114 ciphertext: ct.toString('base64'),
162 ciphertext: ct.toString('base64'),
115 tag: tag.toString('base64'),
163 tag: tag.toString('base64'),
116 };
164 };
117}
165}
118
166
119/** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */
167/** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */
120function makeClientKeyPair() {
168function makeClientKeyPair ()
169{
121 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
170 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
122 modulusLength: 2048,
171 modulusLength: 2048,
123 publicKeyEncoding: { type: 'spki', format: 'pem' },
172 publicKeyEncoding: { type: 'spki', format: 'pem' },
124 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
173 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
125 });
174 });
126 const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
175 const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
@@ -128,12 +177,13 @@ function makeClientKeyPair() {
128}
177}
129
178
130/** Decrypt the token the server sends back. */
179/** Decrypt the token the server sends back. */
131function clientDecrypt(payload, privateKey) {
180function clientDecrypt (payload, privateKey)
181{
132 const ek = Buffer.from(payload.encryptedKey, 'base64');
182 const ek = Buffer.from(payload.encryptedKey, 'base64');
133 const iv = Buffer.from(payload.iv, 'base64');
183 const iv = Buffer.from(payload.iv, 'base64');
134 const ct = Buffer.from(payload.ciphertext, 'base64');
184 const ct = Buffer.from(payload.ciphertext, 'base64');
135 const tg = Buffer.from(payload.tag, 'base64');
185 const tg = Buffer.from(payload.tag, 'base64');
136 const rawAes = crypto.privateDecrypt(
186 const rawAes = crypto.privateDecrypt(
137 { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
187 { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
138 ek,
188 ek,
139 );
189 );
@@ -144,28 +194,34 @@ function clientDecrypt(payload, privateKey) {
144
194
145// ── tests ──────────────────────────────────────────────────────────────────
195// ── tests ──────────────────────────────────────────────────────────────────
146
196
147describe('GET /api/auth/server-key', () => {
197describe('GET /api/auth/server-key', () =>
148 test('returns a JWK public key', async () => {
198{
199 test('returns a JWK public key', async () =>
200 {
149 const { status, body } = await get('/api/auth/server-key');
201 const { status, body } = await get('/api/auth/server-key');
150 expect(status).toBe(200);
202 expect(status).toBe(200);
151 expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) });
203 expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) });
152 });
204 });
153});
205});
154
206
155describe('GET /api/auth/setup-needed', () => {
207describe('GET /api/auth/setup-needed', () =>
156 test('returns needed=true when no users exist', async () => {
208{
209 test('returns needed=true when no users exist', async () =>
210 {
157 const { status, body } = await get('/api/auth/setup-needed');
211 const { status, body } = await get('/api/auth/setup-needed');
158 expect(status).toBe(200);
212 expect(status).toBe(200);
159 expect(body.needed).toBe(true);
213 expect(body.needed).toBe(true);
160 });
214 });
161});
215});
162
216
163describe('POST /api/auth/setup', () => {
217describe('POST /api/auth/setup', () =>
218{
164 let kp;
219 let kp;
165
220
166 beforeAll(() => { kp = makeClientKeyPair(); });
221 beforeAll(() => { kp = makeClientKeyPair(); });
167
222
168 test('rejects weak password', async () => {
223 test('rejects weak password', async () =>
224 {
169 const encrypted = clientEncrypt({ username: 'admin', password: 'short' });
225 const encrypted = clientEncrypt({ username: 'admin', password: 'short' });
170 const { status, body } = await post('/api/auth/setup', {
226 const { status, body } = await post('/api/auth/setup', {
171 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
227 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -173,7 +229,8 @@ describe('POST /api/auth/setup', () => {
173 expect(status).toBe(400);
229 expect(status).toBe(400);
174 });
230 });
175
231
176 test('creates admin and returns encrypted token', async () => {
232 test('creates admin and returns encrypted token', async () =>
233 {
177 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
234 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
178 const { status, body } = await post('/api/auth/setup', {
235 const { status, body } = await post('/api/auth/setup', {
179 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
236 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -181,9 +238,9 @@ describe('POST /api/auth/setup', () => {
181 expect(status).toBe(200);
238 expect(status).toBe(200);
182 expect(body.encrypted).toMatchObject({
239 expect(body.encrypted).toMatchObject({
183 encryptedKey: expect.any(String),
240 encryptedKey: expect.any(String),
184 iv: expect.any(String),
241 iv: expect.any(String),
185 ciphertext: expect.any(String),
242 ciphertext: expect.any(String),
186 tag: expect.any(String),
243 tag: expect.any(String),
187 });
244 });
188
245
189 // Token should be a valid JWT string
246 // Token should be a valid JWT string
@@ -191,13 +248,15 @@ describe('POST /api/auth/setup', () => {
191 expect(token.split('.').length).toBe(3);
248 expect(token.split('.').length).toBe(3);
192 });
249 });
193
250
194 test('setup-needed is now false', async () => {
251 test('setup-needed is now false', async () =>
252 {
195 const { body } = await get('/api/auth/setup-needed');
253 const { body } = await get('/api/auth/setup-needed');
196 expect(body.needed).toBe(false);
254 expect(body.needed).toBe(false);
197 });
255 });
198
256
199 test('cannot run setup again once a user exists', async () => {
257 test('cannot run setup again once a user exists', async () =>
200 const kp2 = makeClientKeyPair();
258 {
259 const kp2 = makeClientKeyPair();
201 const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' });
260 const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' });
202 const { status } = await post('/api/auth/setup', {
261 const { status } = await post('/api/auth/setup', {
203 encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test',
262 encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test',
@@ -206,11 +265,13 @@ describe('POST /api/auth/setup', () => {
206 });
265 });
207});
266});
208
267
209describe('POST /api/auth/login', () => {
268describe('POST /api/auth/login', () =>
269{
210 let kp;
270 let kp;
211 beforeAll(() => { kp = makeClientKeyPair(); });
271 beforeAll(() => { kp = makeClientKeyPair(); });
212
272
213 test('rejects wrong password', async () => {
273 test('rejects wrong password', async () =>
274 {
214 const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' });
275 const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' });
215 const { status } = await post('/api/auth/login', {
276 const { status } = await post('/api/auth/login', {
216 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
277 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -218,7 +279,8 @@ describe('POST /api/auth/login', () => {
218 expect(status).toBe(401);
279 expect(status).toBe(401);
219 });
280 });
220
281
221 test('returns encrypted token on correct credentials', async () => {
282 test('returns encrypted token on correct credentials', async () =>
283 {
222 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
284 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
223 const { status, body } = await post('/api/auth/login', {
285 const { status, body } = await post('/api/auth/login', {
224 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
286 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
@@ -228,7 +290,8 @@ describe('POST /api/auth/login', () => {
228 expect(token.split('.').length).toBe(3);
290 expect(token.split('.').length).toBe(3);
229 });
291 });
230
292
231 test('rejects invalid encrypted payload', async () => {
293 test('rejects invalid encrypted payload', async () =>
294 {
232 const { status } = await post('/api/auth/login', {
295 const { status } = await post('/api/auth/login', {
233 encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' },
296 encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' },
234 clientPublicKey: kp.publicKeyJwk,
297 clientPublicKey: kp.publicKeyJwk,
@@ -237,3 +300,57 @@ describe('POST /api/auth/login', () => {
237 expect(status).toBe(400);
300 expect(status).toBe(400);
238 });
301 });
239});
302});
303
304describe('session lifecycle', () =>
305{
306 const fingerprint = 'test';
307
308 async function loginAndGetToken ()
309 {
310 const kp = makeClientKeyPair();
311 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
312 const { status, body } = await post('/api/auth/login', {
313 encrypted,
314 clientPublicKey: kp.publicKeyJwk,
315 fingerprint,
316 });
317 expect(status).toBe(200);
318 return clientDecrypt(body.encrypted, kp.privateKey);
319 }
320
321 test('POST /api/auth/logout revokes active session', async () =>
322 {
323 const token = await loginAndGetToken();
324
325 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
326 expect(meBefore.status).toBe(200);
327
328 const logout = await authed('POST', '/api/auth/logout', token, fingerprint, {});
329 expect(logout.status).toBe(200);
330 expect(logout.body.ok).toBe(true);
331
332 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
333 expect(meAfter.status).toBe(401);
334 });
335
336 test('session expires after 1 hour of inactivity', async () =>
337 {
338 const token = await loginAndGetToken();
339
340 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
341 expect(meBefore.status).toBe(200);
342
343 const realNow = Date.now;
344 try
345 {
346 const jumped = realNow() + SESSION_IDLE_TIMEOUT_MS + 1000;
347 Date.now = jest.fn(() => jumped);
348
349 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
350 expect(meAfter.status).toBe(401);
351 } finally
352 {
353 Date.now = realNow;
354 }
355 });
356});