BlueGit

timfa filemanager

Files

filemanager / .github / technical-reference.md

technical-reference.md

technical-reference.md 9.6 KiB Download Raw

Technical Reference

server/index.js

  • start() - Initialises DB/keys, loads config, starts HTTP server (config.port) and optional HTTPS server (config.httpsPort + config.tlsCert + config.tlsKey). Both share the same Express app.
  • shutdown(opts, ...servers) - Graceful teardown: closes DB, closes all provided http/https Server instances, and exits with configurable code after drain/timeout.

server/db.js

  • initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
  • getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
  • closeDb() - Closes singleton DB handle to release file locks.

server/auth.js

  • createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.
  • requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
  • requireAdmin(req, res, next) - Requires authenticated admin user.
  • revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
  • getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
  • getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
  • SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).

server/routes/auth.js

  • extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
  • makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.
  • POST /api/auth/setup - Creates first admin and issues token.
  • POST /api/auth/login - Authenticates user by case-insensitive username match and issues token with canonical stored username.
  • GET /api/auth/me - Returns current authenticated user profile.
  • POST /api/auth/logout - Revokes the active session.

server/routes/admin.js

  • POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.

server/routes/files.js

  • GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
  • POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).

public/app.js

  • showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
  • getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
  • getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
  • saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
  • loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
  • api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
  • performLogout() - Explicit logout path that revokes server session and clears local session state.
  • initAuth() - Restores prior session when valid and auto-logins without credential prompt.
  • showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
  • showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
  • showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
  • loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
  • loadOneThumbnail(iconEl) - Injects clipped in-icon thumbnails: real previews for image/video/text where feasible and generated badges for other file types.
  • getThumbnailKind(name) - Classifies files into thumbnail strategy buckets (image/video/text/audio/pdf/badge).
  • buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (blob URL/data URL) for icon injection.
  • detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
  • prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
  • highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
  • fileAccentColor(name) - Returns canonical file-type accent color used by icon strokes and preview sheet outline.
  • openFolderSidebar() - Persistent sidebar fallback view that shows current folder/root overview when no item is selected.
  • closeSidebar() - Clears selection; hides the panel entirely on mobile and restores folder overview sidebar on desktop.
  • isMobileViewport() - Central media-query helper for mobile-only sidebar/interaction behavior.
  • hideSidebarPanel() - Hides sidebar panel and removes sidebar-open layout class from the app shell.
  • renderBreadcrumb() - Builds clickable breadcrumb path and marks each folder segment as a drag-drop move target via .crumb-drop-target and data-path.
  • fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
  • downloadOrView(item, sourceSvgEl) - Opens preview; prefers in-place expanded tile preview when invoked from a file icon, falls back to overlay when no source tile is available.
  • downloadOrView(item, sourceSvgEl) - Opens in-place expanded tile preview from a file icon; shows error toast if no source tile is found.
  • renderPreviewBody(item, blob, objectUrl, targetEl) - Renders preview content (image/video/audio/pdf/text) or unsupported message into a target container.
  • animateRect(el, fromRect, toRect, opts) - Helper that animates element rectangle (left/top/width/height) for expand/collapse transitions.
  • openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents the real file tile to body, expands it to viewport preview, injects close/download controls.
  • openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents tile to body, shows spinner during expand animation, renders content after animation; applies file-type accent colour to tile border and outline glow.
  • closeExpandedTilePreview() - Collapses expanded tile preview back to original grid position and restores original icon markup.
  • closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
  • closePreview() - Closes expanded-tile preview and revokes active preview object URL.
  • openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
  • rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
  • ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
  • createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
  • loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
  • isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
  • makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
  • attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
  • openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
  • openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.

public/drag-move.js

  • makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
  • (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
  • (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
  • (internal) _endDrag() - On valid target: runs drop animation on real tile then calls POST /api/files/move, refreshes dir. Otherwise snap-back.
  • (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.

public/drag-move.css

  • .file-item.dragging - Lifted style for real dragged tile.
  • .file-item.drop-target - Glows folder icon when drag hovers over it.
  • .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
  • .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
  • @keyframes drag-rise-spin-fall - Real tile rises, spins, falls/scales into folder on drop.
  • @keyframes folder-bounce - Target folder bounces down then back on accept.
  • .preview-backdrop/.file-item--preview/.preview-expand-* - In-place expanded tile preview styling (no separate overlay window), including preserved icon-outline layer.
  • .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.

tests/auth.routes.test.js

  • session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
  • session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.
Source
1# Technical Reference
2
3## server/index.js
4- start() - Initialises DB/keys, loads config, starts HTTP server (config.port) and optional HTTPS server (config.httpsPort + config.tlsCert + config.tlsKey). Both share the same Express app.
5- shutdown(opts, ...servers) - Graceful teardown: closes DB, closes all provided http/https Server instances, and exits with configurable code after drain/timeout.
6
7## server/db.js
8- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
9- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
10- closeDb() - Closes singleton DB handle to release file locks.
11
12## server/auth.js
13- createToken(username, req, fingerprint) - Creates JWT bound to IP/region/fingerprint and linked to a DB-backed session id.
14- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
15- requireAdmin(req, res, next) - Requires authenticated admin user.
16- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
17- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
18- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
19- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
20
21## server/routes/auth.js
22- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
23- makeAuthResponse(token, clientPublicKey) - Returns encrypted token when client key exists, plaintext token otherwise.
24- POST /api/auth/setup - Creates first admin and issues token.
25- POST /api/auth/login - Authenticates user by case-insensitive username match and issues token with canonical stored username.
26- GET /api/auth/me - Returns current authenticated user profile.
27- POST /api/auth/logout - Revokes the active session.
28
29## server/routes/admin.js
30- POST /api/admin/users - Creates a new user and enforces case-insensitive username uniqueness.
31
32## server/routes/files.js
33- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
34- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
35
36## public/app.js
37- showApp() - Reveals app shell; keeps sidebar folded by default on mobile and shows folder overview sidebar on desktop.
38- getOrCreateClientBindingId() - Creates/loads a persistent local browser binding id used in auth fingerprint derivation.
39- getFingerprint() - Builds a stable fingerprint from binding id + stable browser properties (not viewport metrics) to avoid false session invalidation on UI/window-state changes.
40- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
41- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
42- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
43- performLogout() - Explicit logout path that revokes server session and clears local session state.
44- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
45- showConfirm(title, message) - In-page confirm dialog; returns Promise<boolean>. Use instead of window.confirm().
46- showPrompt(title, message, defaultValue) - In-page text-input dialog; returns Promise<string|null>. Use instead of window.prompt().
47- showOverwrite(filename) - In-page overwrite-decision dialog for file conflicts; returns Promise<'yes'|'no'|'all'|'none'>.
48- loadThumbnails() - Loads per-file image thumbnails into file SVG icons after grid rendering.
49- loadOneThumbnail(iconEl) - Injects clipped in-icon thumbnails: real previews for image/video/text where feasible and generated badges for other file types.
50- getThumbnailKind(name) - Classifies files into thumbnail strategy buckets (image/video/text/audio/pdf/badge).
51- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (blob URL/data URL) for icon injection.
52- detectCodeLanguage(name, mime) - Determines preview language for text/script files by MIME and extension.
53- prettyPrintCode(raw, lang) - Best-effort formatter for JSON/markup/script previews before rendering.
54- highlightCode(raw, lang) - Escapes and syntax-highlights preview text into HTML spans.
55- fileAccentColor(name) - Returns canonical file-type accent color used by icon strokes and preview sheet outline.
56- openFolderSidebar() - Persistent sidebar fallback view that shows current folder/root overview when no item is selected.
57- closeSidebar() - Clears selection; hides the panel entirely on mobile and restores folder overview sidebar on desktop.
58- isMobileViewport() - Central media-query helper for mobile-only sidebar/interaction behavior.
59- hideSidebarPanel() - Hides sidebar panel and removes sidebar-open layout class from the app shell.
60- renderBreadcrumb() - Builds clickable breadcrumb path and marks each folder segment as a drag-drop move target via .crumb-drop-target and data-path.
61- fetchFileBlob(item) - Downloads a file as Blob with auth headers for preview/download flows.
62- downloadOrView(item, sourceSvgEl) - Opens preview; prefers in-place expanded tile preview when invoked from a file icon, falls back to overlay when no source tile is available.
63- downloadOrView(item, sourceSvgEl) - Opens in-place expanded tile preview from a file icon; shows error toast if no source tile is found.
64- renderPreviewBody(item, blob, objectUrl, targetEl) - Renders preview content (image/video/audio/pdf/text) or unsupported message into a target container.
65- animateRect(el, fromRect, toRect, opts) - Helper that animates element rectangle (left/top/width/height) for expand/collapse transitions.
66- openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents the real file tile to body, expands it to viewport preview, injects close/download controls.
67- openExpandedTilePreview(item, tileEl, sourceSvgEl, blob, objectUrl) - Reparents tile to body, shows spinner during expand animation, renders content after animation; applies file-type accent colour to tile border and outline glow.
68- closeExpandedTilePreview() - Collapses expanded tile preview back to original grid position and restores original icon markup.
69- closePreview() - Closes either expanded-tile preview or overlay preview, then revokes active preview object URL.
70- closePreview() - Closes expanded-tile preview and revokes active preview object URL.
71- openMovePicker(item) - Opens Move To selector modal with expandable folder tree across all writable roots and executes /api/files/move.
72- rootPermissionLabel(root) - Resolves permission key for a root using originalName when available (alias-safe permission checks).
73- ensureMoveModal() - Lazily creates and wires Move To modal UI (tree, selection state, confirm/cancel handlers).
74- createMoveNode(folderPath, label) - Builds an expandable/selectable folder node for the Move To tree.
75- loadMoveChildren(containerEl, dirPath) - Lazy-loads subfolders for a tree node via /api/files/list.
76- isInlinePreviewableBlob(blob, name) - Determines if a blob can be previewed inline by MIME/extension.
77- makeFileItem(item) - Builds a .file-item element; roots in Home now use folder-like interaction (single-click focus, double-click open), roots are non-draggable, and mobile long-press contextmenu suppression remains.
78- attachMobileLongPress(el, item) - Adds mobile long-press detection on file/folder tiles to open the item sidebar without desktop side effects.
79- openSidebar(item) - Renders item details/actions in sidebar; roots show alias + original name + usage stats, hide Move To/Delete, keep Rename.
80- openRenameModal(item) - Renames files/folders; for roots this writes display alias via /api/files/root-alias and reloads roots.
81
82## public/drag-move.js
83- makeDraggable(el, item) - Attaches pointerdown to a .file-item; starts drag after threshold movement. Depends on: api(), canWrite(), navigateTo(), STATE, closeSidebar(), toast() from app.js.
84- (internal) _beginDrag(e, el, item) - Lifts and re-parents the real .file-item to body, inserts hidden placeholder, and shows parent-folder drag target when applicable.
85- (internal) _moveDrag(e) - Moves the real dragged item, hit-tests folder tiles, breadcrumb segments, and parent-folder target, toggles target highlight state.
86- (internal) _endDrag() - On valid target: runs drop animation on real tile then calls POST /api/files/move, refreshes dir. Otherwise snap-back.
87- (internal) _cleanupDrag(reinsert) - Restores tile styles; reinserts into grid on failure/abort or removes before refresh on success, hides drag helper targets.
88
89## public/drag-move.css
90- .file-item.dragging - Lifted style for real dragged tile.
91- .file-item.drop-target - Glows folder icon when drag hovers over it.
92- .drag-parent-target - Temporary top-left "move to parent" drop target shown while dragging in nested folders.
93- .crumb-drop-target.active - Highlight style for breadcrumb drop destinations during drag.
94- @keyframes drag-rise-spin-fall - Real tile rises, spins, falls/scales into folder on drop.
95- @keyframes folder-bounce - Target folder bounces down then back on accept.
96- .preview-backdrop/.file-item--preview/.preview-expand-* - In-place expanded tile preview styling (no separate overlay window), including preserved icon-outline layer.
97- .move-modal/.move-tree/.move-node* - Move To tree picker styles with expandable/collapsible folder hierarchy.
98
99## tests/auth.routes.test.js
100- session lifecycle / POST /api/auth/logout revokes active session - Verifies explicit logout invalidates token immediately.
101- session lifecycle / session expires after 1 hour of inactivity - Verifies server-side idle timeout enforcement.