Merge feature/in-page-modals: in-page modal system + Linux drag-drop fix
@@ -0,0 +1,39 @@
1
# Technical Reference
2
3
## server/db.js
4
- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
5
- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
6
- closeDb() - Closes singleton DB handle to release file locks.
7
8
## server/auth.js
9
- createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.
10
- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
11
- requireAdmin(req, res, next) - Requires authenticated admin user.
12
- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
13
- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
14
- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
15
- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
16
17
## server/routes/auth.js
18
- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
19
- makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.
20
- POST /api/auth/setup - Creates first admin and issues token.
21
- POST /api/auth/login - Authenticates user and issues token.
22
- GET /api/auth/me - Returns current authenticated user profile.
23
- POST /api/auth/logout - Revokes the active session.
24
25
## public/app.js
26
- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
27
- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
28
- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
29
- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
30
- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
31
- performLogout() - Explicit logout path that revokes server session and clears local session state.
32
- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
33
- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
34
- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
35
- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
36
37
## tests/auth.routes.test.js
38
- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
39
- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
@@ -0,0 +1,39 @@1
# Technical Reference2
3
## server/db.js4
- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).5
- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.6
- closeDb() - Closes singleton DB handle to release file locks.7
8
## server/auth.js9
- createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.10
- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.11
- requireAdmin(req, res, next) - Requires authenticated admin user.12
- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.13
- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).14
- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.15
- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).16
17
## server/routes/auth.js18
- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.19
- makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.20
- POST /api/auth/setup - Creates first admin and issues token.21
- POST /api/auth/login - Authenticates user and issues token.22
- GET /api/auth/me - Returns current authenticated user profile.23
- POST /api/auth/logout - Revokes the active session.24
25
## public/app.js26
- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.27
- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.28
- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.29
- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.30
- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.31
- performLogout() - Explicit logout path that revokes server session and clears local session state.32
- initAuth() - Restores prior session when valid and auto-logins without credential prompt.33
- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().34
- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().35
- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.36
37
## tests/auth.routes.test.js38
- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.39
- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.@@ -3,7 +3,7 @@
3
3
=========================================================
4
4
Architecture:
5
5
- RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API
6
- No cookies / sessionStorage — token lives in module-scoped memory
6
- Token is stored in localStorage to survive full page refresh
7
7
- Token is sent as Bearer header on every API call
8
8
- Fingerprint (derived from navigator info) locks the token to this browser
9
9
========================================================= */
@@ -29,13 +29,30 @@ const STATE = {
29
29
30
30
// Server public key for encrypting login
31
31
serverPublicKeyJwk: null,
32
33
// Stable per-browser binding id used in fingerprint derivation
34
clientBindingId: null,
35
36
// Persisted view state
37
restoreDir: null,
38
restoreRootPath: null,
39
lastOperationAt: null,
40
41
// Background refresh state
42
autoRefreshTimer: null,
43
uploadInProgress: false,
32
44
};
33
45
46
const SESSION_KEY = 'filemanager.session.v1';
47
const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
48
const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';
49
34
50
// ───────────────────────────────────────────────────────────────────────────
35
51
// CRYPTO HELPERS (Web Crypto API)
36
52
// ───────────────────────────────────────────────────────────────────────────
37
53
38
54
async function generateClientKeyPair() {
55
if (!hasWebCrypto()) return;
39
56
const kp = await crypto.subtle.generateKey(
40
57
{ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' },
41
58
true,
@@ -50,6 +67,10 @@ async function generateClientKeyPair() {
50
67
* Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.
51
68
*/
52
69
async function hybridEncryptForServer(obj) {
70
if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) {
71
return { plaintext: obj };
72
}
73
53
74
const serverPub = await crypto.subtle.importKey(
54
75
'jwk', STATE.serverPublicKeyJwk,
55
76
{ name: 'RSA-OAEP', hash: 'SHA-256' },
@@ -81,6 +102,10 @@ async function hybridEncryptForServer(obj) {
81
102
* Hybrid-decrypt a payload encrypted by the server for us (using our public key).
82
103
*/
83
104
async function hybridDecryptFromServer(payload) {
105
if (!payload) return null;
106
if (payload.token) return payload.token;
107
if (!hasWebCrypto()) return null;
108
84
109
const encryptedKey = unb64(payload.encryptedKey);
85
110
const iv = unb64(payload.iv);
86
111
const ciphertext = unb64(payload.ciphertext);
@@ -109,6 +134,10 @@ function b64(buf) {
109
134
return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));
110
135
}
111
136
137
function hasWebCrypto() {
138
return !!(window.crypto && window.crypto.subtle);
139
}
140
112
141
function unb64(str) {
113
142
const binary = atob(str);
114
143
const buf = new Uint8Array(binary.length);
@@ -118,17 +147,56 @@ function unb64(str) {
118
147
119
148
/** Stable browser fingerprint (not stored, derived fresh each load) */
120
149
function getFingerprint() {
150
const binding = getOrCreateClientBindingId();
121
151
const nav = navigator;
152
153
// Keep this stable: avoid viewport/screen metrics that can change when
154
// devtools opens, orientation changes, or window state changes.
122
155
return [
156
binding,
157
nav.userAgent || '',
123
158
nav.language,
124
159
nav.platform || nav.userAgentData?.platform || '',
125
nav.hardwareConcurrency,
126
screen.colorDepth,
127
screen.width + 'x' + screen.height,
128
160
Intl.DateTimeFormat().resolvedOptions().timeZone,
129
161
].join('|');
130
162
}
131
163
164
function randomIdHex(bytes = 16) {
165
const arr = new Uint8Array(bytes);
166
if (window.crypto && typeof window.crypto.getRandomValues === 'function') {
167
window.crypto.getRandomValues(arr);
168
} else {
169
for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);
170
}
171
return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
172
}
173
174
function getOrCreateClientBindingId() {
175
if (STATE.clientBindingId) return STATE.clientBindingId;
176
177
try {
178
const existing = localStorage.getItem(CLIENT_BINDING_KEY);
179
if (existing && typeof existing === 'string') {
180
STATE.clientBindingId = existing;
181
return existing;
182
}
183
} catch {
184
// Ignore storage read errors.
185
}
186
187
const created = randomIdHex(16);
188
STATE.clientBindingId = created;
189
190
try {
191
localStorage.setItem(CLIENT_BINDING_KEY, created);
192
} catch {
193
// Ignore storage write errors; in-memory fallback still keeps this stable
194
// for the current page session.
195
}
196
197
return created;
198
}
199
132
200
function formatBytes(bytes) {
133
201
if (bytes == null) return '—';
134
202
if (bytes < 1024) return bytes + ' B';
@@ -142,28 +210,99 @@ function extOf(name) {
142
210
return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
143
211
}
144
212
213
function getPathSep(basePath) {
214
return basePath && basePath.includes('\\') ? '\\' : '/';
215
}
216
217
function joinServerPath(basePath, segment) {
218
const sep = getPathSep(basePath);
219
const base = String(basePath || '').replace(/[\\/]+$/, '');
220
return base + sep + segment;
221
}
222
223
function samePath(a, b) {
224
if (!a || !b) return false;
225
return String(a).toLowerCase() === String(b).toLowerCase();
226
}
227
228
function pathInside(child, root) {
229
if (!child || !root) return false;
230
if (samePath(child, root)) return true;
231
const sep = getPathSep(root);
232
return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());
233
}
234
235
function saveSessionState() {
236
if (!STATE.token) return;
237
const now = Date.now();
238
STATE.lastOperationAt = now;
239
const payload = {
240
token: STATE.token,
241
dir: STATE.currentDir || null,
242
rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,
243
lastOperationAt: STATE.lastOperationAt,
244
};
245
try {
246
localStorage.setItem(SESSION_KEY, JSON.stringify(payload));
247
} catch {
248
// Ignore storage errors (private mode/full quota).
249
}
250
}
251
252
function loadSessionState() {
253
try {
254
const raw = localStorage.getItem(SESSION_KEY);
255
if (!raw) return null;
256
const parsed = JSON.parse(raw);
257
if (!parsed || typeof parsed.token !== 'string') return null;
258
if (!Number.isFinite(parsed.lastOperationAt)) return null;
259
260
if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) {
261
clearSessionState();
262
return null;
263
}
264
265
return parsed;
266
} catch {
267
return null;
268
}
269
}
270
271
function clearSessionState() {
272
try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }
273
}
274
145
275
// ───────────────────────────────────────────────────────────────────────────
146
276
// API
147
277
// ───────────────────────────────────────────────────────────────────────────
148
278
149
279
async function api(method, path, body, opts = {}) {
150
280
const headers = { 'Content-Type': 'application/json' };
281
const noAutoLogout = !!opts.noAutoLogout;
151
282
if (STATE.token) {
152
283
headers['Authorization'] = 'Bearer ' + STATE.token;
153
284
headers['X-Fp'] = getFingerprint();
154
285
}
286
const fetchOpts = { ...opts };
287
delete fetchOpts.noAutoLogout;
155
288
const res = await fetch('/api' + path, {
156
289
method,
157
290
headers,
158
291
body: body != null ? JSON.stringify(body) : undefined,
159
...opts,
292
...fetchOpts,
160
293
});
161
294
if (!res.ok) {
162
295
const j = await res.json().catch(() => ({}));
163
296
// Session-expired → force re-login
164
if (res.status === 401) { logout(); return null; }
297
if (res.status === 401) {
298
if (!noAutoLogout) logout();
299
return null;
300
}
165
301
throw new Error(j.error || res.statusText);
166
302
}
303
if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) {
304
saveSessionState();
305
}
167
306
return res.json();
168
307
}
169
308
@@ -179,6 +318,120 @@ function toast(msg, type = '') {
179
318
setTimeout(() => el.remove(), 3500);
180
319
}
181
320
321
// ───────────────────────────────────────────────────────────────────────────
322
// DIALOG MODALS — centralised replacements for alert / confirm / prompt
323
// ───────────────────────────────────────────────────────────────────────────
324
325
/**
326
* Show a confirmation dialog.
327
* @param {string} title
328
* @param {string} message
329
* @returns {Promise<boolean>} true = OK, false = Cancel
330
*/
331
function showConfirm(title, message) {
332
return new Promise((resolve) => {
333
const overlay = document.getElementById('confirm-modal');
334
document.getElementById('confirm-modal-title').textContent = title;
335
document.getElementById('confirm-modal-message').textContent = message;
336
overlay.classList.remove('hidden');
337
338
const ok = document.getElementById('confirm-modal-ok');
339
const cancel = document.getElementById('confirm-modal-cancel');
340
341
function finish(result) {
342
overlay.classList.add('hidden');
343
ok.removeEventListener('click', onOk);
344
cancel.removeEventListener('click', onCancel);
345
resolve(result);
346
}
347
function onOk() { finish(true); }
348
function onCancel() { finish(false); }
349
350
ok.addEventListener('click', onOk);
351
cancel.addEventListener('click', onCancel);
352
ok.focus();
353
});
354
}
355
356
/**
357
* Show a text-input dialog.
358
* @param {string} title
359
* @param {string} [message] — optional helper text shown above the input
360
* @param {string} [defaultValue] — pre-filled value
361
* @returns {Promise<string|null>} string = submitted value, null = cancelled
362
*/
363
function showPrompt(title, message = '', defaultValue = '') {
364
return new Promise((resolve) => {
365
const overlay = document.getElementById('prompt-modal');
366
const msgEl = document.getElementById('prompt-modal-message');
367
const input = document.getElementById('prompt-modal-input');
368
const errorEl = document.getElementById('prompt-modal-error');
369
const form = document.getElementById('prompt-modal-form');
370
const cancel = document.getElementById('prompt-modal-cancel');
371
372
document.getElementById('prompt-modal-title').textContent = title;
373
msgEl.textContent = message;
374
msgEl.classList.toggle('hidden', !message);
375
input.value = defaultValue;
376
errorEl.classList.add('hidden');
377
overlay.classList.remove('hidden');
378
input.focus();
379
input.select();
380
381
function finish(result) {
382
overlay.classList.add('hidden');
383
form.removeEventListener('submit', onSubmit);
384
cancel.removeEventListener('click', onCancel);
385
resolve(result);
386
}
387
function onSubmit(e) {
388
e.preventDefault();
389
finish(input.value);
390
}
391
function onCancel() { finish(null); }
392
393
form.addEventListener('submit', onSubmit);
394
cancel.addEventListener('click', onCancel);
395
});
396
}
397
398
/**
399
* Show an overwrite-decision dialog for a single file conflict.
400
* @param {string} filename
401
* @returns {Promise<'yes'|'no'|'all'|'none'>}
402
*/
403
function showOverwrite(filename) {
404
return new Promise((resolve) => {
405
const overlay = document.getElementById('overwrite-modal');
406
document.getElementById('overwrite-modal-filename').textContent = filename;
407
overlay.classList.remove('hidden');
408
409
const btnYes = document.getElementById('overwrite-modal-yes');
410
const btnNo = document.getElementById('overwrite-modal-no');
411
const btnAll = document.getElementById('overwrite-modal-all');
412
const btnSkipAll = document.getElementById('overwrite-modal-skip-all');
413
414
function finish(result) {
415
overlay.classList.add('hidden');
416
btnYes.removeEventListener('click', onYes);
417
btnNo.removeEventListener('click', onNo);
418
btnAll.removeEventListener('click', onAll);
419
btnSkipAll.removeEventListener('click', onSkipAll);
420
resolve(result);
421
}
422
function onYes() { finish('yes'); }
423
function onNo() { finish('no'); }
424
function onAll() { finish('all'); }
425
function onSkipAll() { finish('none'); }
426
427
btnYes.addEventListener('click', onYes);
428
btnNo.addEventListener('click', onNo);
429
btnAll.addEventListener('click', onAll);
430
btnSkipAll.addEventListener('click', onSkipAll);
431
btnNo.focus();
432
});
433
}
434
182
435
// ───────────────────────────────────────────────────────────────────────────
183
436
// AUTH FLOW
184
437
// ───────────────────────────────────────────────────────────────────────────
@@ -189,7 +442,9 @@ function showAuthOverlay(setupMode = false) {
189
442
overlay.classList.remove('hidden');
190
443
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';
191
444
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);
192
document.getElementById('auth-submit').textContent = setupMode ? 'Create Account' : 'Sign In';
445
const submitBtn = document.getElementById('auth-submit');
446
submitBtn.disabled = false;
447
submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';
193
448
document.getElementById('auth-error').classList.add('hidden');
194
449
document.getElementById('auth-username').value = '';
195
450
document.getElementById('auth-password').value = '';
@@ -201,19 +456,50 @@ function showApp() {
201
456
document.getElementById('auth-overlay').classList.add('hidden');
202
457
document.getElementById('app').classList.remove('hidden');
203
458
document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
459
startAutoRefresh();
204
460
}
205
461
206
462
async function initAuth() {
207
463
// Always generate a fresh key pair so each page-load session is independent
208
await generateClientKeyPair();
464
await generateClientKeyPair().catch(() => {
465
toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');
466
});
209
467
210
468
// Fetch server public key
211
469
const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));
212
if (!publicKey) { toast('Could not reach server.', 'err'); return; }
470
if (publicKey) STATE.serverPublicKeyJwk = publicKey;
471
if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }
213
472
STATE.serverPublicKeyJwk = publicKey;
214
473
215
474
// Check whether first-run setup is needed
216
475
const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));
476
477
if (!needed) {
478
const saved = loadSessionState();
479
if (saved && saved.token) {
480
STATE.token = saved.token;
481
STATE.restoreDir = saved.dir || null;
482
STATE.restoreRootPath = saved.rootPath || null;
483
STATE.lastOperationAt = saved.lastOperationAt;
484
485
const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);
486
if (me) {
487
STATE.username = me.username;
488
STATE.isAdmin = me.isAdmin;
489
STATE.permissions = me.permissions;
490
showApp();
491
await loadRoots({
492
preferredDir: STATE.restoreDir,
493
preferredRootPath: STATE.restoreRootPath,
494
});
495
return;
496
}
497
498
STATE.token = null;
499
clearSessionState();
500
}
501
}
502
217
503
showAuthOverlay(needed);
218
504
}
219
505
@@ -235,7 +521,8 @@ async function doLogin(username, password, isSetup) {
235
521
if (!data) return 'Login failed.';
236
522
237
523
// Decrypt the token sent back by the server
238
const token = await hybridDecryptFromServer(data.encrypted);
524
const token = await hybridDecryptFromServer(data.encrypted || data);
525
if (!token) return 'Login failed.';
239
526
STATE.token = token;
240
527
241
528
// Load user info
@@ -246,12 +533,28 @@ async function doLogin(username, password, isSetup) {
246
533
STATE.isAdmin = me.isAdmin;
247
534
STATE.permissions = me.permissions;
248
535
536
saveSessionState();
249
537
showApp();
250
538
await loadRoots();
251
539
return null; // no error
252
540
}
253
541
254
542
function logout() {
543
void performLogout();
544
}
545
546
async function performLogout() {
547
const tokenAtStart = STATE.token;
548
stopAutoRefresh();
549
550
if (tokenAtStart) {
551
try {
552
await api('POST', '/auth/logout', {}, { noAutoLogout: true });
553
} catch {
554
// Ignore network errors while logging out locally.
555
}
556
}
557
255
558
STATE.token = null;
256
559
STATE.username = null;
257
560
STATE.isAdmin = false;
@@ -259,19 +562,38 @@ function logout() {
259
562
STATE.currentDir = null;
260
563
STATE.currentRoot = null;
261
564
STATE.items = [];
565
STATE.restoreDir = null;
566
STATE.restoreRootPath = null;
567
STATE.lastOperationAt = null;
568
clearSessionState();
262
569
closeSidebar();
263
initAuth();
570
await initAuth();
264
571
}
265
572
266
573
// ───────────────────────────────────────────────────────────────────────────
267
574
// NAVIGATION
268
575
// ───────────────────────────────────────────────────────────────────────────
269
576
270
async function loadRoots() {
577
async function loadRoots(opts = {}) {
271
578
const data = await api('GET', '/files/roots');
272
579
if (!data) return;
273
580
STATE.roots = data.roots;
274
581
582
const preferredDir = opts.preferredDir || null;
583
const preferredRootPath = opts.preferredRootPath || null;
584
585
if (preferredDir && preferredRootPath) {
586
const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));
587
if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) {
588
try {
589
await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });
590
return;
591
} catch {
592
// Fall back to default root behavior.
593
}
594
}
595
}
596
275
597
if (STATE.roots.length === 1) {
276
598
// Single root → open it directly
277
599
await navigateTo(STATE.roots[0].path, STATE.roots[0]);
@@ -283,10 +605,12 @@ async function loadRoots() {
283
605
function renderRootsView() {
284
606
STATE.currentDir = null;
285
607
STATE.currentRoot = null;
608
saveSessionState();
286
609
renderBreadcrumb();
287
610
const grid = document.getElementById('file-grid');
288
611
grid.innerHTML = '';
289
612
document.getElementById('empty-notice').classList.add('hidden');
613
document.getElementById('folder-stats').classList.add('hidden');
290
614
closeSidebar();
291
615
292
616
for (const root of STATE.roots) {
@@ -295,7 +619,7 @@ function renderRootsView() {
295
619
}
296
620
}
297
621
298
async function navigateTo(absPath, root) {
622
async function navigateTo(absPath, root, opts = {}) {
299
623
if (root) STATE.currentRoot = root;
300
624
STATE.currentDir = absPath;
301
625
@@ -303,9 +627,11 @@ async function navigateTo(absPath, root) {
303
627
if (!data) return;
304
628
305
629
STATE.items = data.items;
630
saveSessionState();
306
631
renderBreadcrumb();
307
632
renderFileGrid();
308
closeSidebar();
633
await refreshFolderStats();
634
if (!opts.keepSidebar) closeSidebar();
309
635
}
310
636
311
637
function renderBreadcrumb() {
@@ -363,6 +689,74 @@ function renderBreadcrumb() {
363
689
}
364
690
}
365
691
692
async function refreshFolderStats() {
693
const el = document.getElementById('folder-stats');
694
if (!STATE.currentDir) {
695
el.classList.add('hidden');
696
return;
697
}
698
699
const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
700
if (!data) {
701
el.classList.add('hidden');
702
return;
703
}
704
705
const used = formatBytes(data.usedBytes);
706
const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);
707
el.textContent = `Folder usage (recursive): ${used} | Free on root: ${free}`;
708
el.classList.remove('hidden');
709
}
710
711
function itemsSignature(items) {
712
return JSON.stringify(
713
(items || []).map(it => [it.path, it.mtime, it.size, it.isDir])
714
.sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
715
);
716
}
717
718
async function incrementalRefreshCurrentDir() {
719
if (!STATE.currentDir || STATE.uploadInProgress) return;
720
const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);
721
if (!data) return;
722
723
const oldSig = itemsSignature(STATE.items);
724
const newSig = itemsSignature(data.items);
725
if (oldSig !== newSig) {
726
const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;
727
STATE.items = data.items;
728
renderFileGrid();
729
730
if (selectedPath) {
731
const match = STATE.items.find(i => i.path === selectedPath);
732
if (match) {
733
const selectedEl = Array.from(document.querySelectorAll('.file-item'))
734
.find(el => el.dataset.path === selectedPath);
735
if (selectedEl) selectItem(selectedEl, match);
736
} else {
737
closeSidebar();
738
}
739
}
740
}
741
742
await refreshFolderStats();
743
}
744
745
function startAutoRefresh() {
746
stopAutoRefresh();
747
STATE.autoRefreshTimer = setInterval(() => {
748
if (document.hidden) return;
749
incrementalRefreshCurrentDir();
750
}, 5000);
751
}
752
753
function stopAutoRefresh() {
754
if (STATE.autoRefreshTimer) {
755
clearInterval(STATE.autoRefreshTimer);
756
STATE.autoRefreshTimer = null;
757
}
758
}
759
366
760
// ───────────────────────────────────────────────────────────────────────────
367
761
// FILE GRID RENDERING
368
762
// ───────────────────────────────────────────────────────────────────────────
@@ -552,6 +946,7 @@ async function uploadFiles(fileList) {
552
946
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
553
947
if (!canWrite()) { toast('No write access.', 'err'); return; }
554
948
949
const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);
555
950
const formData = new FormData();
556
951
for (const f of fileList) formData.append('files', f);
557
952
@@ -560,12 +955,14 @@ async function uploadFiles(fileList) {
560
955
wrap.className = 'upload-bar-wrap';
561
956
wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
562
957
document.body.appendChild(wrap);
958
STATE.uploadInProgress = true;
563
959
564
960
try {
565
961
const xhr = new XMLHttpRequest();
566
962
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);
567
963
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
568
964
xhr.setRequestHeader('X-Fp', getFingerprint());
965
xhr.setRequestHeader('X-Upload-Size', String(totalSize));
569
966
570
967
xhr.upload.addEventListener('progress', e => {
571
968
if (e.lengthComputable) {
@@ -587,6 +984,95 @@ async function uploadFiles(fileList) {
587
984
} catch (err) {
588
985
toast(err.message, 'err');
589
986
} finally {
987
STATE.uploadInProgress = false;
988
wrap.remove();
989
}
990
}
991
992
async function uploadSingleFile(file, targetDir) {
993
const formData = new FormData();
994
formData.append('files', file);
995
996
await new Promise((resolve, reject) => {
997
const xhr = new XMLHttpRequest();
998
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
999
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
1000
xhr.setRequestHeader('X-Fp', getFingerprint());
1001
xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));
1002
xhr.onload = () => xhr.status === 200
1003
? resolve()
1004
: reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
1005
xhr.onerror = () => reject(new Error('Network error'));
1006
xhr.send(formData);
1007
});
1008
}
1009
1010
async function ensureServerDir(baseDir, relativeDir) {
1011
const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);
1012
let current = baseDir;
1013
for (const part of parts) {
1014
try {
1015
const resp = await api('POST', '/files/mkdir', { dir: current, name: part });
1016
current = resp && resp.path ? resp.path : joinServerPath(current, part);
1017
} catch (err) {
1018
if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1019
current = joinServerPath(current, part);
1020
}
1021
}
1022
return current;
1023
}
1024
1025
async function uploadFolderInputFiles(fileList) {
1026
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1027
if (!canWrite()) { toast('No write access.', 'err'); return; }
1028
if (!fileList || !fileList.length) return;
1029
1030
const files = Array.from(fileList);
1031
const total = files.length;
1032
let done = 0;
1033
1034
const wrap = document.createElement('div');
1035
wrap.className = 'upload-bar-wrap';
1036
wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
1037
document.body.appendChild(wrap);
1038
STATE.uploadInProgress = true;
1039
1040
try {
1041
const dirCache = new Map();
1042
dirCache.set('', STATE.currentDir);
1043
1044
for (const file of files) {
1045
const rel = file.webkitRelativePath || file.name;
1046
const relParts = rel.split(/[\\/]/).filter(Boolean);
1047
const relDir = relParts.slice(0, -1).join('/');
1048
1049
if (!dirCache.has(relDir)) {
1050
const parentRel = relParts.slice(0, -2).join('/');
1051
const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);
1052
const thisName = relParts[relParts.length - 2];
1053
1054
try {
1055
const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });
1056
dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));
1057
} catch (err) {
1058
if (!/exist|EEXIST/i.test(err.message || '')) throw err;
1059
dirCache.set(relDir, joinServerPath(parentAbs, thisName));
1060
}
1061
}
1062
1063
const targetDir = dirCache.get(relDir) || STATE.currentDir;
1064
await uploadSingleFile(file, targetDir);
1065
done++;
1066
wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;
1067
wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';
1068
}
1069
1070
toast(`Uploaded ${total} file(s).`, 'ok');
1071
await navigateTo(STATE.currentDir, STATE.currentRoot);
1072
} catch (err) {
1073
toast(err.message, 'err');
1074
} finally {
1075
STATE.uploadInProgress = false;
590
1076
wrap.remove();
591
1077
}
592
1078
}
@@ -619,7 +1105,7 @@ function readAllEntries(reader) {
619
1105
*/
620
1106
async function collectEntries(entry, serverDir, toUpload) {
621
1107
if (entry.isFile) {
622
const file = await new Promise((res, rej) => entry.getFile(res, rej));
1108
const file = await new Promise((res, rej) => entry.file(res, rej));
623
1109
toUpload.push({ file, targetDir: serverDir });
624
1110
} else if (entry.isDirectory) {
625
1111
// Ask the server to create the directory; it returns the canonical path.
@@ -652,6 +1138,7 @@ async function uploadEntries(entries) {
652
1138
wrap.className = 'upload-bar-wrap';
653
1139
wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;
654
1140
document.body.appendChild(wrap);
1141
STATE.uploadInProgress = true;
655
1142
656
1143
try {
657
1144
const toUpload = [];
@@ -670,19 +1157,7 @@ async function uploadEntries(entries) {
670
1157
updateBar();
671
1158
672
1159
for (const { file, targetDir } of toUpload) {
673
const formData = new FormData();
674
formData.append('files', file);
675
await new Promise((resolve, reject) => {
676
const xhr = new XMLHttpRequest();
677
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);
678
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);
679
xhr.setRequestHeader('X-Fp', getFingerprint());
680
xhr.onload = () => xhr.status === 200
681
? resolve()
682
: reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));
683
xhr.onerror = () => reject(new Error('Network error'));
684
xhr.send(formData);
685
});
1160
await uploadSingleFile(file, targetDir);
686
1161
done++;
687
1162
updateBar();
688
1163
}
@@ -692,6 +1167,7 @@ async function uploadEntries(entries) {
692
1167
} catch (err) {
693
1168
toast(err.message, 'err');
694
1169
} finally {
1170
STATE.uploadInProgress = false;
695
1171
wrap.remove();
696
1172
}
697
1173
}
@@ -768,7 +1244,7 @@ function openRenameModal(item) {
768
1244
// ───────────────────────────────────────────────────────────────────────────
769
1245
770
1246
async function deleteItem(item) {
771
if (!confirm(`Delete "${item.name}"? This cannot be undone.`)) return;
1247
if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;
772
1248
try {
773
1249
await api('POST', '/files/delete', { path: item.path });
774
1250
toast('Deleted.', 'ok');
@@ -827,7 +1303,7 @@ async function refreshAdminUsers() {
827
1303
row.querySelector('[data-action="edit"]').addEventListener('click', () =>
828
1304
openUserModal(u, paths));
829
1305
row.querySelector('[data-action="delete"]').addEventListener('click', async () => {
830
if (!confirm(`Delete user "${u.username}"?`)) return;
1306
if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;
831
1307
try {
832
1308
await api('DELETE', `/admin/users/${u.id}`);
833
1309
toast('User deleted.', 'ok');
@@ -988,6 +1464,12 @@ function wireEvents() {
988
1464
// Logout
989
1465
document.getElementById('btn-logout').addEventListener('click', logout);
990
1466
1467
// Hard refresh while keeping auth/session state.
1468
document.getElementById('btn-refresh').addEventListener('click', () => {
1469
saveSessionState();
1470
location.reload();
1471
});
1472
991
1473
// Upload button
992
1474
document.getElementById('btn-upload').addEventListener('click', () => {
993
1475
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
@@ -1000,6 +1482,38 @@ function wireEvents() {
1000
1482
e.target.value = '';
1001
1483
});
1002
1484
1485
document.getElementById('btn-upload-folder').addEventListener('click', () => {
1486
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1487
if (!canWrite()) { toast('No write access.', 'err'); return; }
1488
document.getElementById('folder-input').click();
1489
});
1490
1491
document.getElementById('folder-input').addEventListener('change', async (e) => {
1492
if (e.target.files.length) await uploadFolderInputFiles(e.target.files);
1493
e.target.value = '';
1494
});
1495
1496
document.getElementById('btn-new-folder').addEventListener('click', async () => {
1497
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }
1498
if (!canWrite()) { toast('No write access.', 'err'); return; }
1499
1500
const name = await showPrompt('New Folder', 'Enter a name for the new folder:');
1501
if (name == null) return;
1502
const folderName = name.trim();
1503
if (!folderName) {
1504
toast('Folder name is required.', 'err');
1505
return;
1506
}
1507
1508
try {
1509
await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });
1510
toast('Folder created.', 'ok');
1511
await navigateTo(STATE.currentDir, STATE.currentRoot);
1512
} catch (err) {
1513
toast(err.message, 'err');
1514
}
1515
});
1516
1003
1517
// Sidebar close
1004
1518
document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
1005
1519
@@ -1038,7 +1552,7 @@ function wireEvents() {
1038
1552
1039
1553
// Shutdown server
1040
1554
document.getElementById('admin-shutdown-btn').addEventListener('click', async () => {
1041
if (!confirm('Shut down the server? You will lose access until it is restarted manually.')) return;
1555
if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;
1042
1556
try {
1043
1557
await api('POST', '/admin/shutdown');
1044
1558
toast('Server is shutting down…', 'ok');
@@ -1080,5 +1594,6 @@ function wireEvents() {
1080
1594
(async function boot() {
1081
1595
wireEvents();
1082
1596
initDragDrop();
1597
window.addEventListener('beforeunload', saveSessionState);
1083
1598
await initAuth();
1084
1599
})();
@@ -3,7 +3,7 @@3
=========================================================3
=========================================================4
Architecture:4
Architecture:5
- RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API5
- RSA-OAEP + AES-256-GCM hybrid encryption via Web Crypto API6
- No cookies / sessionStorage — token lives in module-scoped memory6
- Token is stored in localStorage to survive full page refresh7
- Token is sent as Bearer header on every API call7
- Token is sent as Bearer header on every API call8
- Fingerprint (derived from navigator info) locks the token to this browser8
- Fingerprint (derived from navigator info) locks the token to this browser9
========================================================= */9
========================================================= */@@ -29,13 +29,30 @@ const STATE = {29
29
30
// Server public key for encrypting login30
// Server public key for encrypting login31
serverPublicKeyJwk: null,31
serverPublicKeyJwk: null,32
33
// Stable per-browser binding id used in fingerprint derivation34
clientBindingId: null,35
36
// Persisted view state37
restoreDir: null,38
restoreRootPath: null,39
lastOperationAt: null,40
41
// Background refresh state42
autoRefreshTimer: null,43
uploadInProgress: false,32
};44
};33
45
46
const SESSION_KEY = 'filemanager.session.v1';47
const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour48
const CLIENT_BINDING_KEY = 'filemanager.client-binding-id.v1';49
34
// ───────────────────────────────────────────────────────────────────────────50
// ───────────────────────────────────────────────────────────────────────────35
// CRYPTO HELPERS (Web Crypto API)51
// CRYPTO HELPERS (Web Crypto API)36
// ───────────────────────────────────────────────────────────────────────────52
// ───────────────────────────────────────────────────────────────────────────37
53
38
async function generateClientKeyPair() {54
async function generateClientKeyPair() {55
if (!hasWebCrypto()) return;39
const kp = await crypto.subtle.generateKey(56
const kp = await crypto.subtle.generateKey(40
{ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' },57
{ name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1,0,1]), hash: 'SHA-256' },41
true,58
true,@@ -50,6 +67,10 @@ async function generateClientKeyPair() {50
* Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.67
* Returns { encryptedKey, iv, ciphertext, tag } all as base64 strings.51
*/68
*/52
async function hybridEncryptForServer(obj) {69
async function hybridEncryptForServer(obj) {70
if (!hasWebCrypto() || !STATE.serverPublicKeyJwk) {71
return { plaintext: obj };72
}73
53
const serverPub = await crypto.subtle.importKey(74
const serverPub = await crypto.subtle.importKey(54
'jwk', STATE.serverPublicKeyJwk,75
'jwk', STATE.serverPublicKeyJwk,55
{ name: 'RSA-OAEP', hash: 'SHA-256' },76
{ name: 'RSA-OAEP', hash: 'SHA-256' },@@ -81,6 +102,10 @@ async function hybridEncryptForServer(obj) {81
* Hybrid-decrypt a payload encrypted by the server for us (using our public key).102
* Hybrid-decrypt a payload encrypted by the server for us (using our public key).82
*/103
*/83
async function hybridDecryptFromServer(payload) {104
async function hybridDecryptFromServer(payload) {105
if (!payload) return null;106
if (payload.token) return payload.token;107
if (!hasWebCrypto()) return null;108
84
const encryptedKey = unb64(payload.encryptedKey);109
const encryptedKey = unb64(payload.encryptedKey);85
const iv = unb64(payload.iv);110
const iv = unb64(payload.iv);86
const ciphertext = unb64(payload.ciphertext);111
const ciphertext = unb64(payload.ciphertext);@@ -109,6 +134,10 @@ function b64(buf) {109
return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));134
return btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf.buffer)));110
}135
}111
136
137
function hasWebCrypto() {138
return !!(window.crypto && window.crypto.subtle);139
}140
112
function unb64(str) {141
function unb64(str) {113
const binary = atob(str);142
const binary = atob(str);114
const buf = new Uint8Array(binary.length);143
const buf = new Uint8Array(binary.length);@@ -118,17 +147,56 @@ function unb64(str) {118
147
119
/** Stable browser fingerprint (not stored, derived fresh each load) */148
/** Stable browser fingerprint (not stored, derived fresh each load) */120
function getFingerprint() {149
function getFingerprint() {150
const binding = getOrCreateClientBindingId();121
const nav = navigator;151
const nav = navigator;152
153
// Keep this stable: avoid viewport/screen metrics that can change when154
// devtools opens, orientation changes, or window state changes.122
return [155
return [156
binding,157
nav.userAgent || '',123
nav.language,158
nav.language,124
nav.platform || nav.userAgentData?.platform || '',159
nav.platform || nav.userAgentData?.platform || '',125
nav.hardwareConcurrency,126
screen.colorDepth,127
screen.width + 'x' + screen.height,128
Intl.DateTimeFormat().resolvedOptions().timeZone,160
Intl.DateTimeFormat().resolvedOptions().timeZone,129
].join('|');161
].join('|');130
}162
}131
163
164
function randomIdHex(bytes = 16) {165
const arr = new Uint8Array(bytes);166
if (window.crypto && typeof window.crypto.getRandomValues === 'function') {167
window.crypto.getRandomValues(arr);168
} else {169
for (let i = 0; i < arr.length; i++) arr[i] = Math.floor(Math.random() * 256);170
}171
return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');172
}173
174
function getOrCreateClientBindingId() {175
if (STATE.clientBindingId) return STATE.clientBindingId;176
177
try {178
const existing = localStorage.getItem(CLIENT_BINDING_KEY);179
if (existing && typeof existing === 'string') {180
STATE.clientBindingId = existing;181
return existing;182
}183
} catch {184
// Ignore storage read errors.185
}186
187
const created = randomIdHex(16);188
STATE.clientBindingId = created;189
190
try {191
localStorage.setItem(CLIENT_BINDING_KEY, created);192
} catch {193
// Ignore storage write errors; in-memory fallback still keeps this stable194
// for the current page session.195
}196
197
return created;198
}199
132
function formatBytes(bytes) {200
function formatBytes(bytes) {133
if (bytes == null) return '—';201
if (bytes == null) return '—';134
if (bytes < 1024) return bytes + ' B';202
if (bytes < 1024) return bytes + ' B';@@ -142,28 +210,99 @@ function extOf(name) {142
return i >= 0 ? name.slice(i + 1).toLowerCase() : '';210
return i >= 0 ? name.slice(i + 1).toLowerCase() : '';143
}211
}144
212
213
function getPathSep(basePath) {214
return basePath && basePath.includes('\\') ? '\\' : '/';215
}216
217
function joinServerPath(basePath, segment) {218
const sep = getPathSep(basePath);219
const base = String(basePath || '').replace(/[\\/]+$/, '');220
return base + sep + segment;221
}222
223
function samePath(a, b) {224
if (!a || !b) return false;225
return String(a).toLowerCase() === String(b).toLowerCase();226
}227
228
function pathInside(child, root) {229
if (!child || !root) return false;230
if (samePath(child, root)) return true;231
const sep = getPathSep(root);232
return String(child).toLowerCase().startsWith((String(root) + sep).toLowerCase());233
}234
235
function saveSessionState() {236
if (!STATE.token) return;237
const now = Date.now();238
STATE.lastOperationAt = now;239
const payload = {240
token: STATE.token,241
dir: STATE.currentDir || null,242
rootPath: STATE.currentRoot ? STATE.currentRoot.path : null,243
lastOperationAt: STATE.lastOperationAt,244
};245
try {246
localStorage.setItem(SESSION_KEY, JSON.stringify(payload));247
} catch {248
// Ignore storage errors (private mode/full quota).249
}250
}251
252
function loadSessionState() {253
try {254
const raw = localStorage.getItem(SESSION_KEY);255
if (!raw) return null;256
const parsed = JSON.parse(raw);257
if (!parsed || typeof parsed.token !== 'string') return null;258
if (!Number.isFinite(parsed.lastOperationAt)) return null;259
260
if (Date.now() - parsed.lastOperationAt > SESSION_IDLE_TIMEOUT_MS) {261
clearSessionState();262
return null;263
}264
265
return parsed;266
} catch {267
return null;268
}269
}270
271
function clearSessionState() {272
try { localStorage.removeItem(SESSION_KEY); } catch { /* ignore */ }273
}274
145
// ───────────────────────────────────────────────────────────────────────────275
// ───────────────────────────────────────────────────────────────────────────146
// API276
// API147
// ───────────────────────────────────────────────────────────────────────────277
// ───────────────────────────────────────────────────────────────────────────148
278
149
async function api(method, path, body, opts = {}) {279
async function api(method, path, body, opts = {}) {150
const headers = { 'Content-Type': 'application/json' };280
const headers = { 'Content-Type': 'application/json' };281
const noAutoLogout = !!opts.noAutoLogout;151
if (STATE.token) {282
if (STATE.token) {152
headers['Authorization'] = 'Bearer ' + STATE.token;283
headers['Authorization'] = 'Bearer ' + STATE.token;153
headers['X-Fp'] = getFingerprint();284
headers['X-Fp'] = getFingerprint();154
}285
}286
const fetchOpts = { ...opts };287
delete fetchOpts.noAutoLogout;155
const res = await fetch('/api' + path, {288
const res = await fetch('/api' + path, {156
method,289
method,157
headers,290
headers,158
body: body != null ? JSON.stringify(body) : undefined,291
body: body != null ? JSON.stringify(body) : undefined,159
...opts,292
...fetchOpts,160
});293
});161
if (!res.ok) {294
if (!res.ok) {162
const j = await res.json().catch(() => ({}));295
const j = await res.json().catch(() => ({}));163
// Session-expired → force re-login296
// Session-expired → force re-login164
if (res.status === 401) { logout(); return null; }297
if (res.status === 401) {298
if (!noAutoLogout) logout();299
return null;300
}165
throw new Error(j.error || res.statusText);301
throw new Error(j.error || res.statusText);166
}302
}303
if (STATE.token && !path.startsWith('/auth/server-key') && !path.startsWith('/auth/setup-needed')) {304
saveSessionState();305
}167
return res.json();306
return res.json();168
}307
}169
308
@@ -179,6 +318,120 @@ function toast(msg, type = '') {179
setTimeout(() => el.remove(), 3500);318
setTimeout(() => el.remove(), 3500);180
}319
}181
320
321
// ───────────────────────────────────────────────────────────────────────────322
// DIALOG MODALS — centralised replacements for alert / confirm / prompt323
// ───────────────────────────────────────────────────────────────────────────324
325
/**326
* Show a confirmation dialog.327
* @param {string} title328
* @param {string} message329
* @returns {Promise<boolean>} true = OK, false = Cancel330
*/331
function showConfirm(title, message) {332
return new Promise((resolve) => {333
const overlay = document.getElementById('confirm-modal');334
document.getElementById('confirm-modal-title').textContent = title;335
document.getElementById('confirm-modal-message').textContent = message;336
overlay.classList.remove('hidden');337
338
const ok = document.getElementById('confirm-modal-ok');339
const cancel = document.getElementById('confirm-modal-cancel');340
341
function finish(result) {342
overlay.classList.add('hidden');343
ok.removeEventListener('click', onOk);344
cancel.removeEventListener('click', onCancel);345
resolve(result);346
}347
function onOk() { finish(true); }348
function onCancel() { finish(false); }349
350
ok.addEventListener('click', onOk);351
cancel.addEventListener('click', onCancel);352
ok.focus();353
});354
}355
356
/**357
* Show a text-input dialog.358
* @param {string} title359
* @param {string} [message] — optional helper text shown above the input360
* @param {string} [defaultValue] — pre-filled value361
* @returns {Promise<string|null>} string = submitted value, null = cancelled362
*/363
function showPrompt(title, message = '', defaultValue = '') {364
return new Promise((resolve) => {365
const overlay = document.getElementById('prompt-modal');366
const msgEl = document.getElementById('prompt-modal-message');367
const input = document.getElementById('prompt-modal-input');368
const errorEl = document.getElementById('prompt-modal-error');369
const form = document.getElementById('prompt-modal-form');370
const cancel = document.getElementById('prompt-modal-cancel');371
372
document.getElementById('prompt-modal-title').textContent = title;373
msgEl.textContent = message;374
msgEl.classList.toggle('hidden', !message);375
input.value = defaultValue;376
errorEl.classList.add('hidden');377
overlay.classList.remove('hidden');378
input.focus();379
input.select();380
381
function finish(result) {382
overlay.classList.add('hidden');383
form.removeEventListener('submit', onSubmit);384
cancel.removeEventListener('click', onCancel);385
resolve(result);386
}387
function onSubmit(e) {388
e.preventDefault();389
finish(input.value);390
}391
function onCancel() { finish(null); }392
393
form.addEventListener('submit', onSubmit);394
cancel.addEventListener('click', onCancel);395
});396
}397
398
/**399
* Show an overwrite-decision dialog for a single file conflict.400
* @param {string} filename401
* @returns {Promise<'yes'|'no'|'all'|'none'>}402
*/403
function showOverwrite(filename) {404
return new Promise((resolve) => {405
const overlay = document.getElementById('overwrite-modal');406
document.getElementById('overwrite-modal-filename').textContent = filename;407
overlay.classList.remove('hidden');408
409
const btnYes = document.getElementById('overwrite-modal-yes');410
const btnNo = document.getElementById('overwrite-modal-no');411
const btnAll = document.getElementById('overwrite-modal-all');412
const btnSkipAll = document.getElementById('overwrite-modal-skip-all');413
414
function finish(result) {415
overlay.classList.add('hidden');416
btnYes.removeEventListener('click', onYes);417
btnNo.removeEventListener('click', onNo);418
btnAll.removeEventListener('click', onAll);419
btnSkipAll.removeEventListener('click', onSkipAll);420
resolve(result);421
}422
function onYes() { finish('yes'); }423
function onNo() { finish('no'); }424
function onAll() { finish('all'); }425
function onSkipAll() { finish('none'); }426
427
btnYes.addEventListener('click', onYes);428
btnNo.addEventListener('click', onNo);429
btnAll.addEventListener('click', onAll);430
btnSkipAll.addEventListener('click', onSkipAll);431
btnNo.focus();432
});433
}434
182
// ───────────────────────────────────────────────────────────────────────────435
// ───────────────────────────────────────────────────────────────────────────183
// AUTH FLOW436
// AUTH FLOW184
// ───────────────────────────────────────────────────────────────────────────437
// ───────────────────────────────────────────────────────────────────────────@@ -189,7 +442,9 @@ function showAuthOverlay(setupMode = false) {189
overlay.classList.remove('hidden');442
overlay.classList.remove('hidden');190
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';443
document.getElementById('auth-title').textContent = setupMode ? 'Create Admin Account' : 'Sign In';191
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);444
document.getElementById('auth-subtitle').classList.toggle('hidden', !setupMode);192
document.getElementById('auth-submit').textContent = setupMode ? 'Create Account' : 'Sign In';445
const submitBtn = document.getElementById('auth-submit');446
submitBtn.disabled = false;447
submitBtn.textContent = setupMode ? 'Create Account' : 'Sign In';193
document.getElementById('auth-error').classList.add('hidden');448
document.getElementById('auth-error').classList.add('hidden');194
document.getElementById('auth-username').value = '';449
document.getElementById('auth-username').value = '';195
document.getElementById('auth-password').value = '';450
document.getElementById('auth-password').value = '';@@ -201,19 +456,50 @@ function showApp() {201
document.getElementById('auth-overlay').classList.add('hidden');456
document.getElementById('auth-overlay').classList.add('hidden');202
document.getElementById('app').classList.remove('hidden');457
document.getElementById('app').classList.remove('hidden');203
document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);458
document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);459
startAutoRefresh();204
}460
}205
461
206
async function initAuth() {462
async function initAuth() {207
// Always generate a fresh key pair so each page-load session is independent463
// Always generate a fresh key pair so each page-load session is independent208
await generateClientKeyPair();464
await generateClientKeyPair().catch(() => {465
toast('Secure crypto unavailable in this browser context; using compatibility login mode.', 'err');466
});209
467
210
// Fetch server public key468
// Fetch server public key211
const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));469
const { publicKey } = await api('GET', '/auth/server-key').catch(() => ({ publicKey: null }));212
if (!publicKey) { toast('Could not reach server.', 'err'); return; }470
if (publicKey) STATE.serverPublicKeyJwk = publicKey;471
if (!publicKey && hasWebCrypto()) { toast('Could not reach server.', 'err'); return; }213
STATE.serverPublicKeyJwk = publicKey;472
STATE.serverPublicKeyJwk = publicKey;214
473
215
// Check whether first-run setup is needed474
// Check whether first-run setup is needed216
const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));475
const { needed } = await api('GET', '/auth/setup-needed').catch(() => ({ needed: false }));476
477
if (!needed) {478
const saved = loadSessionState();479
if (saved && saved.token) {480
STATE.token = saved.token;481
STATE.restoreDir = saved.dir || null;482
STATE.restoreRootPath = saved.rootPath || null;483
STATE.lastOperationAt = saved.lastOperationAt;484
485
const me = await api('GET', '/auth/me', null, { noAutoLogout: true }).catch(() => null);486
if (me) {487
STATE.username = me.username;488
STATE.isAdmin = me.isAdmin;489
STATE.permissions = me.permissions;490
showApp();491
await loadRoots({492
preferredDir: STATE.restoreDir,493
preferredRootPath: STATE.restoreRootPath,494
});495
return;496
}497
498
STATE.token = null;499
clearSessionState();500
}501
}502
217
showAuthOverlay(needed);503
showAuthOverlay(needed);218
}504
}219
505
@@ -235,7 +521,8 @@ async function doLogin(username, password, isSetup) {235
if (!data) return 'Login failed.';521
if (!data) return 'Login failed.';236
522
237
// Decrypt the token sent back by the server523
// Decrypt the token sent back by the server238
const token = await hybridDecryptFromServer(data.encrypted);524
const token = await hybridDecryptFromServer(data.encrypted || data);525
if (!token) return 'Login failed.';239
STATE.token = token;526
STATE.token = token;240
527
241
// Load user info528
// Load user info@@ -246,12 +533,28 @@ async function doLogin(username, password, isSetup) {246
STATE.isAdmin = me.isAdmin;533
STATE.isAdmin = me.isAdmin;247
STATE.permissions = me.permissions;534
STATE.permissions = me.permissions;248
535
536
saveSessionState();249
showApp();537
showApp();250
await loadRoots();538
await loadRoots();251
return null; // no error539
return null; // no error252
}540
}253
541
254
function logout() {542
function logout() {543
void performLogout();544
}545
546
async function performLogout() {547
const tokenAtStart = STATE.token;548
stopAutoRefresh();549
550
if (tokenAtStart) {551
try {552
await api('POST', '/auth/logout', {}, { noAutoLogout: true });553
} catch {554
// Ignore network errors while logging out locally.555
}556
}557
255
STATE.token = null;558
STATE.token = null;256
STATE.username = null;559
STATE.username = null;257
STATE.isAdmin = false;560
STATE.isAdmin = false;@@ -259,19 +562,38 @@ function logout() {259
STATE.currentDir = null;562
STATE.currentDir = null;260
STATE.currentRoot = null;563
STATE.currentRoot = null;261
STATE.items = [];564
STATE.items = [];565
STATE.restoreDir = null;566
STATE.restoreRootPath = null;567
STATE.lastOperationAt = null;568
clearSessionState();262
closeSidebar();569
closeSidebar();263
initAuth();570
await initAuth();264
}571
}265
572
266
// ───────────────────────────────────────────────────────────────────────────573
// ───────────────────────────────────────────────────────────────────────────267
// NAVIGATION574
// NAVIGATION268
// ───────────────────────────────────────────────────────────────────────────575
// ───────────────────────────────────────────────────────────────────────────269
576
270
async function loadRoots() {577
async function loadRoots(opts = {}) {271
const data = await api('GET', '/files/roots');578
const data = await api('GET', '/files/roots');272
if (!data) return;579
if (!data) return;273
STATE.roots = data.roots;580
STATE.roots = data.roots;274
581
582
const preferredDir = opts.preferredDir || null;583
const preferredRootPath = opts.preferredRootPath || null;584
585
if (preferredDir && preferredRootPath) {586
const preferredRoot = STATE.roots.find(r => samePath(r.path, preferredRootPath));587
if (preferredRoot && pathInside(preferredDir, preferredRoot.path)) {588
try {589
await navigateTo(preferredDir, preferredRoot, { keepSidebar: true });590
return;591
} catch {592
// Fall back to default root behavior.593
}594
}595
}596
275
if (STATE.roots.length === 1) {597
if (STATE.roots.length === 1) {276
// Single root → open it directly598
// Single root → open it directly277
await navigateTo(STATE.roots[0].path, STATE.roots[0]);599
await navigateTo(STATE.roots[0].path, STATE.roots[0]);@@ -283,10 +605,12 @@ async function loadRoots() {283
function renderRootsView() {605
function renderRootsView() {284
STATE.currentDir = null;606
STATE.currentDir = null;285
STATE.currentRoot = null;607
STATE.currentRoot = null;608
saveSessionState();286
renderBreadcrumb();609
renderBreadcrumb();287
const grid = document.getElementById('file-grid');610
const grid = document.getElementById('file-grid');288
grid.innerHTML = '';611
grid.innerHTML = '';289
document.getElementById('empty-notice').classList.add('hidden');612
document.getElementById('empty-notice').classList.add('hidden');613
document.getElementById('folder-stats').classList.add('hidden');290
closeSidebar();614
closeSidebar();291
615
292
for (const root of STATE.roots) {616
for (const root of STATE.roots) {@@ -295,7 +619,7 @@ function renderRootsView() {295
}619
}296
}620
}297
621
298
async function navigateTo(absPath, root) {622
async function navigateTo(absPath, root, opts = {}) {299
if (root) STATE.currentRoot = root;623
if (root) STATE.currentRoot = root;300
STATE.currentDir = absPath;624
STATE.currentDir = absPath;301
625
@@ -303,9 +627,11 @@ async function navigateTo(absPath, root) {303
if (!data) return;627
if (!data) return;304
628
305
STATE.items = data.items;629
STATE.items = data.items;630
saveSessionState();306
renderBreadcrumb();631
renderBreadcrumb();307
renderFileGrid();632
renderFileGrid();308
closeSidebar();633
await refreshFolderStats();634
if (!opts.keepSidebar) closeSidebar();309
}635
}310
636
311
function renderBreadcrumb() {637
function renderBreadcrumb() {@@ -363,6 +689,74 @@ function renderBreadcrumb() {363
}689
}364
}690
}365
691
692
async function refreshFolderStats() {693
const el = document.getElementById('folder-stats');694
if (!STATE.currentDir) {695
el.classList.add('hidden');696
return;697
}698
699
const data = await api('GET', `/files/space?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);700
if (!data) {701
el.classList.add('hidden');702
return;703
}704
705
const used = formatBytes(data.usedBytes);706
const free = data.freeBytes == null ? 'unknown' : formatBytes(data.freeBytes);707
el.textContent = `Folder usage (recursive): ${used} | Free on root: ${free}`;708
el.classList.remove('hidden');709
}710
711
function itemsSignature(items) {712
return JSON.stringify(713
(items || []).map(it => [it.path, it.mtime, it.size, it.isDir])714
.sort((a, b) => String(a[0]).localeCompare(String(b[0]))),715
);716
}717
718
async function incrementalRefreshCurrentDir() {719
if (!STATE.currentDir || STATE.uploadInProgress) return;720
const data = await api('GET', `/files/list?dir=${encodeURIComponent(STATE.currentDir)}`).catch(() => null);721
if (!data) return;722
723
const oldSig = itemsSignature(STATE.items);724
const newSig = itemsSignature(data.items);725
if (oldSig !== newSig) {726
const selectedPath = STATE.selectedItem ? STATE.selectedItem.path : null;727
STATE.items = data.items;728
renderFileGrid();729
730
if (selectedPath) {731
const match = STATE.items.find(i => i.path === selectedPath);732
if (match) {733
const selectedEl = Array.from(document.querySelectorAll('.file-item'))734
.find(el => el.dataset.path === selectedPath);735
if (selectedEl) selectItem(selectedEl, match);736
} else {737
closeSidebar();738
}739
}740
}741
742
await refreshFolderStats();743
}744
745
function startAutoRefresh() {746
stopAutoRefresh();747
STATE.autoRefreshTimer = setInterval(() => {748
if (document.hidden) return;749
incrementalRefreshCurrentDir();750
}, 5000);751
}752
753
function stopAutoRefresh() {754
if (STATE.autoRefreshTimer) {755
clearInterval(STATE.autoRefreshTimer);756
STATE.autoRefreshTimer = null;757
}758
}759
366
// ───────────────────────────────────────────────────────────────────────────760
// ───────────────────────────────────────────────────────────────────────────367
// FILE GRID RENDERING761
// FILE GRID RENDERING368
// ───────────────────────────────────────────────────────────────────────────762
// ───────────────────────────────────────────────────────────────────────────@@ -552,6 +946,7 @@ async function uploadFiles(fileList) {552
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }946
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }553
if (!canWrite()) { toast('No write access.', 'err'); return; }947
if (!canWrite()) { toast('No write access.', 'err'); return; }554
948
949
const totalSize = Array.from(fileList).reduce((sum, f) => sum + (f.size || 0), 0);555
const formData = new FormData();950
const formData = new FormData();556
for (const f of fileList) formData.append('files', f);951
for (const f of fileList) formData.append('files', f);557
952
@@ -560,12 +955,14 @@ async function uploadFiles(fileList) {560
wrap.className = 'upload-bar-wrap';955
wrap.className = 'upload-bar-wrap';561
wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;956
wrap.innerHTML = `<span>Uploading ${fileList.length} file(s)…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;562
document.body.appendChild(wrap);957
document.body.appendChild(wrap);958
STATE.uploadInProgress = true;563
959
564
try {960
try {565
const xhr = new XMLHttpRequest();961
const xhr = new XMLHttpRequest();566
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);962
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(STATE.currentDir)}`);567
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);963
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);568
xhr.setRequestHeader('X-Fp', getFingerprint());964
xhr.setRequestHeader('X-Fp', getFingerprint());965
xhr.setRequestHeader('X-Upload-Size', String(totalSize));569
966
570
xhr.upload.addEventListener('progress', e => {967
xhr.upload.addEventListener('progress', e => {571
if (e.lengthComputable) {968
if (e.lengthComputable) {@@ -587,6 +984,95 @@ async function uploadFiles(fileList) {587
} catch (err) {984
} catch (err) {588
toast(err.message, 'err');985
toast(err.message, 'err');589
} finally {986
} finally {987
STATE.uploadInProgress = false;988
wrap.remove();989
}990
}991
992
async function uploadSingleFile(file, targetDir) {993
const formData = new FormData();994
formData.append('files', file);995
996
await new Promise((resolve, reject) => {997
const xhr = new XMLHttpRequest();998
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);999
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);1000
xhr.setRequestHeader('X-Fp', getFingerprint());1001
xhr.setRequestHeader('X-Upload-Size', String(file.size || 0));1002
xhr.onload = () => xhr.status === 2001003
? resolve()1004
: reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));1005
xhr.onerror = () => reject(new Error('Network error'));1006
xhr.send(formData);1007
});1008
}1009
1010
async function ensureServerDir(baseDir, relativeDir) {1011
const parts = String(relativeDir || '').split(/[\\/]/).filter(Boolean);1012
let current = baseDir;1013
for (const part of parts) {1014
try {1015
const resp = await api('POST', '/files/mkdir', { dir: current, name: part });1016
current = resp && resp.path ? resp.path : joinServerPath(current, part);1017
} catch (err) {1018
if (!/exist|EEXIST/i.test(err.message || '')) throw err;1019
current = joinServerPath(current, part);1020
}1021
}1022
return current;1023
}1024
1025
async function uploadFolderInputFiles(fileList) {1026
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }1027
if (!canWrite()) { toast('No write access.', 'err'); return; }1028
if (!fileList || !fileList.length) return;1029
1030
const files = Array.from(fileList);1031
const total = files.length;1032
let done = 0;1033
1034
const wrap = document.createElement('div');1035
wrap.className = 'upload-bar-wrap';1036
wrap.innerHTML = `<span>Preparing folder upload…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;1037
document.body.appendChild(wrap);1038
STATE.uploadInProgress = true;1039
1040
try {1041
const dirCache = new Map();1042
dirCache.set('', STATE.currentDir);1043
1044
for (const file of files) {1045
const rel = file.webkitRelativePath || file.name;1046
const relParts = rel.split(/[\\/]/).filter(Boolean);1047
const relDir = relParts.slice(0, -1).join('/');1048
1049
if (!dirCache.has(relDir)) {1050
const parentRel = relParts.slice(0, -2).join('/');1051
const parentAbs = dirCache.get(parentRel) || await ensureServerDir(STATE.currentDir, parentRel);1052
const thisName = relParts[relParts.length - 2];1053
1054
try {1055
const created = await api('POST', '/files/mkdir', { dir: parentAbs, name: thisName });1056
dirCache.set(relDir, created.path || joinServerPath(parentAbs, thisName));1057
} catch (err) {1058
if (!/exist|EEXIST/i.test(err.message || '')) throw err;1059
dirCache.set(relDir, joinServerPath(parentAbs, thisName));1060
}1061
}1062
1063
const targetDir = dirCache.get(relDir) || STATE.currentDir;1064
await uploadSingleFile(file, targetDir);1065
done++;1066
wrap.querySelector('span').textContent = `Uploading ${done} / ${total} file(s)…`;1067
wrap.querySelector('.upload-bar-fill').style.width = (done / total * 100) + '%';1068
}1069
1070
toast(`Uploaded ${total} file(s).`, 'ok');1071
await navigateTo(STATE.currentDir, STATE.currentRoot);1072
} catch (err) {1073
toast(err.message, 'err');1074
} finally {1075
STATE.uploadInProgress = false;590
wrap.remove();1076
wrap.remove();591
}1077
}592
}1078
}@@ -619,7 +1105,7 @@ function readAllEntries(reader) {619
*/1105
*/620
async function collectEntries(entry, serverDir, toUpload) {1106
async function collectEntries(entry, serverDir, toUpload) {621
if (entry.isFile) {1107
if (entry.isFile) {622
const file = await new Promise((res, rej) => entry.getFile(res, rej));1108
const file = await new Promise((res, rej) => entry.file(res, rej));623
toUpload.push({ file, targetDir: serverDir });1109
toUpload.push({ file, targetDir: serverDir });624
} else if (entry.isDirectory) {1110
} else if (entry.isDirectory) {625
// Ask the server to create the directory; it returns the canonical path.1111
// Ask the server to create the directory; it returns the canonical path.@@ -652,6 +1138,7 @@ async function uploadEntries(entries) {652
wrap.className = 'upload-bar-wrap';1138
wrap.className = 'upload-bar-wrap';653
wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;1139
wrap.innerHTML = `<span>Scanning…</span><div class="upload-bar-track"><div class="upload-bar-fill" style="width:0%"></div></div>`;654
document.body.appendChild(wrap);1140
document.body.appendChild(wrap);1141
STATE.uploadInProgress = true;655
1142
656
try {1143
try {657
const toUpload = [];1144
const toUpload = [];@@ -670,19 +1157,7 @@ async function uploadEntries(entries) {670
updateBar();1157
updateBar();671
1158
672
for (const { file, targetDir } of toUpload) {1159
for (const { file, targetDir } of toUpload) {673
const formData = new FormData();1160
await uploadSingleFile(file, targetDir);674
formData.append('files', file);675
await new Promise((resolve, reject) => {676
const xhr = new XMLHttpRequest();677
xhr.open('POST', `/api/files/upload?dir=${encodeURIComponent(targetDir)}`);678
xhr.setRequestHeader('Authorization', 'Bearer ' + STATE.token);679
xhr.setRequestHeader('X-Fp', getFingerprint());680
xhr.onload = () => xhr.status === 200681
? resolve()682
: reject(new Error((JSON.parse(xhr.responseText) || {}).error || 'Upload failed'));683
xhr.onerror = () => reject(new Error('Network error'));684
xhr.send(formData);685
});686
done++;1161
done++;687
updateBar();1162
updateBar();688
}1163
}@@ -692,6 +1167,7 @@ async function uploadEntries(entries) {692
} catch (err) {1167
} catch (err) {693
toast(err.message, 'err');1168
toast(err.message, 'err');694
} finally {1169
} finally {1170
STATE.uploadInProgress = false;695
wrap.remove();1171
wrap.remove();696
}1172
}697
}1173
}@@ -768,7 +1244,7 @@ function openRenameModal(item) {768
// ───────────────────────────────────────────────────────────────────────────1244
// ───────────────────────────────────────────────────────────────────────────769
1245
770
async function deleteItem(item) {1246
async function deleteItem(item) {771
if (!confirm(`Delete "${item.name}"? This cannot be undone.`)) return;1247
if (!await showConfirm('Delete item', `Delete "${item.name}"? This cannot be undone.`)) return;772
try {1248
try {773
await api('POST', '/files/delete', { path: item.path });1249
await api('POST', '/files/delete', { path: item.path });774
toast('Deleted.', 'ok');1250
toast('Deleted.', 'ok');@@ -827,7 +1303,7 @@ async function refreshAdminUsers() {827
row.querySelector('[data-action="edit"]').addEventListener('click', () =>1303
row.querySelector('[data-action="edit"]').addEventListener('click', () =>828
openUserModal(u, paths));1304
openUserModal(u, paths));829
row.querySelector('[data-action="delete"]').addEventListener('click', async () => {1305
row.querySelector('[data-action="delete"]').addEventListener('click', async () => {830
if (!confirm(`Delete user "${u.username}"?`)) return;1306
if (!await showConfirm('Delete user', `Delete user "${u.username}"? This cannot be undone.`)) return;831
try {1307
try {832
await api('DELETE', `/admin/users/${u.id}`);1308
await api('DELETE', `/admin/users/${u.id}`);833
toast('User deleted.', 'ok');1309
toast('User deleted.', 'ok');@@ -988,6 +1464,12 @@ function wireEvents() {988
// Logout1464
// Logout989
document.getElementById('btn-logout').addEventListener('click', logout);1465
document.getElementById('btn-logout').addEventListener('click', logout);990
1466
1467
// Hard refresh while keeping auth/session state.1468
document.getElementById('btn-refresh').addEventListener('click', () => {1469
saveSessionState();1470
location.reload();1471
});1472
991
// Upload button1473
// Upload button992
document.getElementById('btn-upload').addEventListener('click', () => {1474
document.getElementById('btn-upload').addEventListener('click', () => {993
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }1475
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }@@ -1000,6 +1482,38 @@ function wireEvents() {1000
e.target.value = '';1482
e.target.value = '';1001
});1483
});1002
1484
1485
document.getElementById('btn-upload-folder').addEventListener('click', () => {1486
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }1487
if (!canWrite()) { toast('No write access.', 'err'); return; }1488
document.getElementById('folder-input').click();1489
});1490
1491
document.getElementById('folder-input').addEventListener('change', async (e) => {1492
if (e.target.files.length) await uploadFolderInputFiles(e.target.files);1493
e.target.value = '';1494
});1495
1496
document.getElementById('btn-new-folder').addEventListener('click', async () => {1497
if (!STATE.currentDir) { toast('Open a folder first.', 'err'); return; }1498
if (!canWrite()) { toast('No write access.', 'err'); return; }1499
1500
const name = await showPrompt('New Folder', 'Enter a name for the new folder:');1501
if (name == null) return;1502
const folderName = name.trim();1503
if (!folderName) {1504
toast('Folder name is required.', 'err');1505
return;1506
}1507
1508
try {1509
await api('POST', '/files/mkdir', { dir: STATE.currentDir, name: folderName });1510
toast('Folder created.', 'ok');1511
await navigateTo(STATE.currentDir, STATE.currentRoot);1512
} catch (err) {1513
toast(err.message, 'err');1514
}1515
});1516
1003
// Sidebar close1517
// Sidebar close1004
document.getElementById('sidebar-close').addEventListener('click', closeSidebar);1518
document.getElementById('sidebar-close').addEventListener('click', closeSidebar);1005
1519
@@ -1038,7 +1552,7 @@ function wireEvents() {1038
1552
1039
// Shutdown server1553
// Shutdown server1040
document.getElementById('admin-shutdown-btn').addEventListener('click', async () => {1554
document.getElementById('admin-shutdown-btn').addEventListener('click', async () => {1041
if (!confirm('Shut down the server? You will lose access until it is restarted manually.')) return;1555
if (!await showConfirm('Shut down server', 'Shut down the server? You will lose access until it is restarted manually.')) return;1042
try {1556
try {1043
await api('POST', '/admin/shutdown');1557
await api('POST', '/admin/shutdown');1044
toast('Server is shutting down…', 'ok');1558
toast('Server is shutting down…', 'ok');@@ -1080,5 +1594,6 @@ function wireEvents() {1080
(async function boot() {1594
(async function boot() {1081
wireEvents();1595
wireEvents();1082
initDragDrop();1596
initDragDrop();1597
window.addEventListener('beforeunload', saveSessionState);1083
await initAuth();1598
await initAuth();1084
})();1599
})();@@ -43,6 +43,16 @@
43
43
<nav id="breadcrumb" aria-label="Breadcrumb"></nav>
44
44
</div>
45
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
46
56
<button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">
47
57
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
48
58
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -53,6 +63,27 @@
53
63
Upload
54
64
</button>
55
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>
56
87
57
88
<button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">
58
89
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
@@ -77,6 +108,7 @@
77
108
78
109
<!-- MAIN CONTENT AREA -->
79
110
<main id="main-content">
111
<p id="folder-stats" class="muted hidden"></p>
80
112
81
113
<!-- Drop zone hint shown when dragging files over the main area -->
82
114
<div id="drop-overlay" class="hidden">
@@ -167,6 +199,51 @@
167
199
</div>
168
200
</div>
169
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>
210
</div>
211
</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>
222
<div class="dialog-actions">
223
<button type="button" id="prompt-modal-cancel">Cancel</button>
224
<button type="submit" class="primary">OK</button>
225
</div>
226
</form>
227
</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>
243
</div>
244
</div>
245
</div>
246
170
247
<!-- TOAST -->
171
248
<div id="toast" aria-live="assertive" aria-atomic="true"></div>
172
249
@@ -43,6 +43,16 @@43
<nav id="breadcrumb" aria-label="Breadcrumb"></nav>43
<nav id="breadcrumb" aria-label="Breadcrumb"></nav>44
</div>44
</div>45
<div id="topbar-actions">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
Refresh54
</button>55
46
<button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">56
<button id="btn-upload" class="icon-btn" title="Upload files" aria-label="Upload files">47
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"57
<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">58
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">@@ -53,6 +63,27 @@53
Upload63
Upload54
</button>64
</button>55
<input id="file-input" type="file" multiple class="hidden" aria-hidden="true" />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
Folder76
</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 Folder86
</button>56
87
57
<button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">88
<button id="btn-admin" class="icon-btn hidden" title="Admin panel" aria-label="Admin panel">58
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"89
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"@@ -77,6 +108,7 @@77
108
78
<!-- MAIN CONTENT AREA -->109
<!-- MAIN CONTENT AREA -->79
<main id="main-content">110
<main id="main-content">111
<p id="folder-stats" class="muted hidden"></p>80
112
81
<!-- Drop zone hint shown when dragging files over the main area -->113
<!-- Drop zone hint shown when dragging files over the main area -->82
<div id="drop-overlay" class="hidden">114
<div id="drop-overlay" class="hidden">@@ -167,6 +199,51 @@167
</div>199
</div>168
</div>200
</div>169
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>210
</div>211
</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>222
<div class="dialog-actions">223
<button type="button" id="prompt-modal-cancel">Cancel</button>224
<button type="submit" class="primary">OK</button>225
</div>226
</form>227
</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>243
</div>244
</div>245
</div>246
170
<!-- TOAST -->247
<!-- TOAST -->171
<div id="toast" aria-live="assertive" aria-atomic="true"></div>248
<div id="toast" aria-live="assertive" aria-atomic="true"></div>172
249
@@ -153,6 +153,11 @@ button[type="submit"]:hover,
153
153
position: relative;
154
154
}
155
155
156
#folder-stats {
157
margin-bottom: 0.8rem;
158
font-size: 0.85rem;
159
}
160
156
161
/* Drop overlay */
157
162
#drop-overlay {
158
163
position: absolute; inset: 0;
@@ -398,6 +403,33 @@ button[type="submit"]:hover,
398
403
RESPONSIVE — narrow screens
399
404
========================================================= */
400
405
@media (max-width: 600px) {
406
#topbar {
407
height: auto;
408
min-height: var(--topbar-h);
409
padding: 0.5rem 0.6rem;
410
align-items: flex-start;
411
flex-direction: column;
412
}
413
414
#breadcrumb-wrap {
415
width: 100%;
416
}
417
418
#topbar-actions {
419
width: 100%;
420
flex-wrap: wrap;
421
gap: 0.15rem;
422
}
423
424
.icon-btn {
425
padding: 0.4rem 0.55rem;
426
font-size: 0.82rem;
427
}
428
429
#main-content {
430
padding: 0.9rem;
431
}
432
401
433
#file-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }
402
434
403
435
#app.sidebar-open #main-content { margin-right: 0; }
@@ -413,3 +445,29 @@ button[type="submit"]:hover,
413
445
414
446
.modal { padding: 1.25rem; }
415
447
}
448
449
/* =========================================================
450
DIALOG MODALS (confirm / prompt / overwrite)
451
========================================================= */
452
.dialog-message {
453
color: var(--text-muted);
454
font-size: 0.93rem;
455
margin: 0 0 1.5rem;
456
line-height: 1.5;
457
word-break: break-word;
458
}
459
460
.dialog-actions {
461
display: flex;
462
gap: 0.6rem;
463
justify-content: flex-end;
464
flex-wrap: wrap;
465
}
466
467
.dialog-actions--overwrite {
468
justify-content: space-between;
469
}
470
471
.dialog-actions button {
472
min-width: 5rem;
473
}
@@ -153,6 +153,11 @@ button[type="submit"]:hover,153
position: relative;153
position: relative;154
}154
}155
155
156
#folder-stats {157
margin-bottom: 0.8rem;158
font-size: 0.85rem;159
}160
156
/* Drop overlay */161
/* Drop overlay */157
#drop-overlay {162
#drop-overlay {158
position: absolute; inset: 0;163
position: absolute; inset: 0;@@ -398,6 +403,33 @@ button[type="submit"]:hover,398
RESPONSIVE — narrow screens403
RESPONSIVE — narrow screens399
========================================================= */404
========================================================= */400
@media (max-width: 600px) {405
@media (max-width: 600px) {406
#topbar {407
height: auto;408
min-height: var(--topbar-h);409
padding: 0.5rem 0.6rem;410
align-items: flex-start;411
flex-direction: column;412
}413
414
#breadcrumb-wrap {415
width: 100%;416
}417
418
#topbar-actions {419
width: 100%;420
flex-wrap: wrap;421
gap: 0.15rem;422
}423
424
.icon-btn {425
padding: 0.4rem 0.55rem;426
font-size: 0.82rem;427
}428
429
#main-content {430
padding: 0.9rem;431
}432
401
#file-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }433
#file-grid { grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); }402
434
403
#app.sidebar-open #main-content { margin-right: 0; }435
#app.sidebar-open #main-content { margin-right: 0; }@@ -413,3 +445,29 @@ button[type="submit"]:hover,413
445
414
.modal { padding: 1.25rem; }446
.modal { padding: 1.25rem; }415
}447
}448
449
/* =========================================================450
DIALOG MODALS (confirm / prompt / overwrite)451
========================================================= */452
.dialog-message {453
color: var(--text-muted);454
font-size: 0.93rem;455
margin: 0 0 1.5rem;456
line-height: 1.5;457
word-break: break-word;458
}459
460
.dialog-actions {461
display: flex;462
gap: 0.6rem;463
justify-content: flex-end;464
flex-wrap: wrap;465
}466
467
.dialog-actions--overwrite {468
justify-content: space-between;469
}470
471
.dialog-actions button {472
min-width: 5rem;473
}