BlueGit

timfa filemanager

Add uptime cleanup loops

Server maintenance now removes stale auth sessions and expired share links automatically during long runtimes. The app also prunes stale zip cache files in the background so disk usage and DB row growth stay under control over weeks of uptime.

timfa Tim Falken · pushed by timfa

Authored 2026-05-27 · 5 months ago

Hash
7a0f5d0050537283499c9b7d435c01f540848aac
Parent
e5014e60
7 files changed +206 −1
.github/technical-reference.md +8 −0
@@ -8,6 +8,7 @@
8 8 ## server/index.js
9 9 - start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
10 10 - shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
11 - start()/shutdown() - Also starts/stops background auth-session and share-token maintenance loops so stale DB rows and zip cache files are trimmed during long uptime.
11 12 - Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
12 13 - GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
13 14
@@ -53,9 +54,13 @@
53 54 - requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
54 55 - requireAdmin(req, res, next) - Requires authenticated admin user.
55 56 - revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
57 - purgeStaleSessions({ nowMs }) - Physically deletes stale `auth_sessions` rows: revoked sessions older than 24 hours and idle sessions older than idle-timeout + 24 hours.
58 - startAuthSessionCleanupLoop() - Starts a 15-minute background purge loop for stale `auth_sessions` rows and runs one purge immediately on startup.
59 - stopAuthSessionCleanupLoop() - Stops the background auth-session purge loop during server shutdown.
56 60 - getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
57 61 - getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
58 62 - SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
63 - AUTH_SESSION_PURGE_INTERVAL_MS / AUTH_SESSION_REVOKED_RETENTION_MS / AUTH_SESSION_IDLE_RETENTION_MS - Environment-agnostic constants controlling stale auth-session purge cadence and retention windows.
59 64
60 65 ## server/routes/auth.js
61 66 - extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
@@ -148,6 +153,9 @@
148 153 - buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
149 154 - buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
150 155 - pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
156 - purgeExpiredShareTokens({ nowMs }) - Deletes expired `share_tokens` rows so old public links do not accumulate in SQLite.
157 - startShareMaintenanceLoop() / stopShareMaintenanceLoop() - Runs periodic share maintenance every 30 minutes: purge expired share tokens and prune stale zip-cache files; started/stopped from server lifecycle.
158 - runShareMaintenanceOnce() - Single-run helper used at startup and by the periodic share maintenance interval.
151 159 - ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
152 160
153 161 ## server/video-stream.js
@@ -8,6 +8,7 @@
8## server/index.js
8## server/index.js
9- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
9- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
10- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
10- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
11- start()/shutdown() - Also starts/stops background auth-session and share-token maintenance loops so stale DB rows and zip cache files are trimmed during long uptime.
11- Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
12- Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
12- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
13- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
13
14
@@ -53,9 +54,13 @@
53- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
54- requireAuth(req, res, next) - Verifies JWT + binding + session row + 1-hour idle timeout, updates last_seen_at, and attaches req.user.
54- requireAdmin(req, res, next) - Requires authenticated admin user.
55- requireAdmin(req, res, next) - Requires authenticated admin user.
55- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
56- revokeSession(sessionId) - Revokes a session row so future token use fails immediately.
57- purgeStaleSessions({ nowMs }) - Physically deletes stale `auth_sessions` rows: revoked sessions older than 24 hours and idle sessions older than idle-timeout + 24 hours.
58- startAuthSessionCleanupLoop() - Starts a 15-minute background purge loop for stale `auth_sessions` rows and runs one purge immediately on startup.
59- stopAuthSessionCleanupLoop() - Stops the background auth-session purge loop during server shutdown.
56- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
60- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
57- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
61- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
58- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
62- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
63- AUTH_SESSION_PURGE_INTERVAL_MS / AUTH_SESSION_REVOKED_RETENTION_MS / AUTH_SESSION_IDLE_RETENTION_MS - Environment-agnostic constants controlling stale auth-session purge cadence and retention windows.
59
64
60## server/routes/auth.js
65## server/routes/auth.js
61- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
66- extractCredentials(body) - Accepts encrypted payloads and compatibility plaintext payloads for login/setup.
@@ -148,6 +153,9 @@
148- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
153- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
149- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
154- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
150- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
155- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
156- purgeExpiredShareTokens({ nowMs }) - Deletes expired `share_tokens` rows so old public links do not accumulate in SQLite.
157- startShareMaintenanceLoop() / stopShareMaintenanceLoop() - Runs periodic share maintenance every 30 minutes: purge expired share tokens and prune stale zip-cache files; started/stopped from server lifecycle.
158- runShareMaintenanceOnce() - Single-run helper used at startup and by the periodic share maintenance interval.
151- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
159- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
152
160
153## server/video-stream.js
161## server/video-stream.js
.github/tests.md +2 −0
@@ -26,6 +26,7 @@
26 26 - `POST /api/auth/login`
27 27 - `session lifecycle`
28 28 - `POST /api/auth/change-password`
29 - `auth session cleanup`
29 30
30 31 ---
31 32
@@ -83,6 +84,7 @@
83 84 - `GET /api/share/video-stream/:token`
84 85 - `GET /api/share/download/:token`
85 86 - `pruneZipCache`
87 - `purgeExpiredShareTokens`
86 88 - `buildShareOpenGraphPage`
87 89
88 90 ---
@@ -26,6 +26,7 @@
26- `POST /api/auth/login`
26- `POST /api/auth/login`
27- `session lifecycle`
27- `session lifecycle`
28- `POST /api/auth/change-password`
28- `POST /api/auth/change-password`
29- `auth session cleanup`
29
30
30---
31---
31
32
@@ -83,6 +84,7 @@
83- `GET /api/share/video-stream/:token`
84- `GET /api/share/video-stream/:token`
84- `GET /api/share/download/:token`
85- `GET /api/share/download/:token`
85- `pruneZipCache`
86- `pruneZipCache`
87- `purgeExpiredShareTokens`
86- `buildShareOpenGraphPage`
88- `buildShareOpenGraphPage`
87
89
88---
90---
server/auth.js +64 −0
@@ -6,6 +6,11 @@ const geoip = require('geoip-lite');
6 6 const { getDb } = require('./db');
7 7
8 8 const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
9 const AUTH_SESSION_PURGE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
10 const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
11 const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
12
13 let authSessionPurgeTimer = null;
9 14
10 15 // Secret used to sign JWTs — generated fresh each server boot.
11 16 // Tokens from a previous boot are automatically invalid.
@@ -70,6 +75,59 @@ function revokeSession (sessionId)
70 75 .run([nowMs(), sessionId]);
71 76 }
72 77
78 function purgeStaleSessions (opts = {})
79 {
80 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : nowMs();
81 const revokedCutoffMs = now - AUTH_SESSION_REVOKED_RETENTION_MS;
82 const idleCutoffMs = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS;
83 const db = getDb();
84
85 const result = db.prepare(`
86 DELETE FROM auth_sessions
87 WHERE (revoked_at IS NOT NULL AND revoked_at <= ?)
88 OR (last_seen_at <= ?)
89 `).run([revokedCutoffMs, idleCutoffMs]);
90
91 return Number(result && result.changes || 0);
92 }
93
94 function startAuthSessionCleanupLoop ()
95 {
96 if (authSessionPurgeTimer) return;
97
98 // Run once immediately at startup to trim stale rows from earlier uptime.
99 try
100 {
101 purgeStaleSessions();
102 } catch
103 {
104 // Ignore purge failures and retry on the next interval.
105 }
106
107 authSessionPurgeTimer = setInterval(() =>
108 {
109 try
110 {
111 purgeStaleSessions();
112 } catch
113 {
114 // Keep server healthy even if cleanup temporarily fails.
115 }
116 }, AUTH_SESSION_PURGE_INTERVAL_MS);
117
118 if (authSessionPurgeTimer && typeof authSessionPurgeTimer.unref === 'function')
119 {
120 authSessionPurgeTimer.unref();
121 }
122 }
123
124 function stopAuthSessionCleanupLoop ()
125 {
126 if (!authSessionPurgeTimer) return;
127 clearInterval(authSessionPurgeTimer);
128 authSessionPurgeTimer = null;
129 }
130
73 131 // ---------------------------------------------------------------------------
74 132 // Token creation
75 133 // ---------------------------------------------------------------------------
@@ -217,5 +275,11 @@ module.exports = {
217 275 getClientIp,
218 276 getRegion,
219 277 revokeSession,
278 purgeStaleSessions,
279 startAuthSessionCleanupLoop,
280 stopAuthSessionCleanupLoop,
220 281 SESSION_IDLE_TIMEOUT_MS,
282 AUTH_SESSION_PURGE_INTERVAL_MS,
283 AUTH_SESSION_REVOKED_RETENTION_MS,
284 AUTH_SESSION_IDLE_RETENTION_MS,
221 285 };
@@ -6,6 +6,11 @@ const geoip = require('geoip-lite');
6const { getDb } = require('./db');
6const { getDb } = require('./db');
7
7
8const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
8const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
9const AUTH_SESSION_PURGE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
10const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
11const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
12
13let authSessionPurgeTimer = null;
9
14
10// Secret used to sign JWTs — generated fresh each server boot.
15// Secret used to sign JWTs — generated fresh each server boot.
11// Tokens from a previous boot are automatically invalid.
16// Tokens from a previous boot are automatically invalid.
@@ -70,6 +75,59 @@ function revokeSession (sessionId)
70 .run([nowMs(), sessionId]);
75 .run([nowMs(), sessionId]);
71}
76}
72
77
78function purgeStaleSessions (opts = {})
79{
80 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : nowMs();
81 const revokedCutoffMs = now - AUTH_SESSION_REVOKED_RETENTION_MS;
82 const idleCutoffMs = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS;
83 const db = getDb();
84
85 const result = db.prepare(`
86 DELETE FROM auth_sessions
87 WHERE (revoked_at IS NOT NULL AND revoked_at <= ?)
88 OR (last_seen_at <= ?)
89 `).run([revokedCutoffMs, idleCutoffMs]);
90
91 return Number(result && result.changes || 0);
92}
93
94function startAuthSessionCleanupLoop ()
95{
96 if (authSessionPurgeTimer) return;
97
98 // Run once immediately at startup to trim stale rows from earlier uptime.
99 try
100 {
101 purgeStaleSessions();
102 } catch
103 {
104 // Ignore purge failures and retry on the next interval.
105 }
106
107 authSessionPurgeTimer = setInterval(() =>
108 {
109 try
110 {
111 purgeStaleSessions();
112 } catch
113 {
114 // Keep server healthy even if cleanup temporarily fails.
115 }
116 }, AUTH_SESSION_PURGE_INTERVAL_MS);
117
118 if (authSessionPurgeTimer && typeof authSessionPurgeTimer.unref === 'function')
119 {
120 authSessionPurgeTimer.unref();
121 }
122}
123
124function stopAuthSessionCleanupLoop ()
125{
126 if (!authSessionPurgeTimer) return;
127 clearInterval(authSessionPurgeTimer);
128 authSessionPurgeTimer = null;
129}
130
73// ---------------------------------------------------------------------------
131// ---------------------------------------------------------------------------
74// Token creation
132// Token creation
75// ---------------------------------------------------------------------------
133// ---------------------------------------------------------------------------
@@ -217,5 +275,11 @@ module.exports = {
217 getClientIp,
275 getClientIp,
218 getRegion,
276 getRegion,
219 revokeSession,
277 revokeSession,
278 purgeStaleSessions,
279 startAuthSessionCleanupLoop,
280 stopAuthSessionCleanupLoop,
220 SESSION_IDLE_TIMEOUT_MS,
281 SESSION_IDLE_TIMEOUT_MS,
282 AUTH_SESSION_PURGE_INTERVAL_MS,
283 AUTH_SESSION_REVOKED_RETENTION_MS,
284 AUTH_SESSION_IDLE_RETENTION_MS,
221};
285};
server/index.js +6 −0
@@ -7,6 +7,7 @@ const http = require('http');
7 7 const https = require('https');
8 8 const { initDb, closeDb } = require('./db');
9 9 const { ensureServerKeys } = require('./crypto');
10 const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
10 11 const { loadConfig } = require('./config');
11 12 const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
12 13 const { logError } = require('./logger');
@@ -14,6 +15,7 @@ const authRoutes = require('./routes/auth');
14 15 const filesRoutes = require('./routes/files');
15 16 const adminRoutes = require('./routes/admin');
16 17 const shareRoutes = require('./routes/share');
18 const { startShareMaintenanceLoop, stopShareMaintenanceLoop } = require('./routes/share');
17 19
18 20 const app = express();
19 21
@@ -62,6 +64,8 @@ function shutdown (opts = {}, ...servers)
62 64 active.forEach(s => { s.__isShuttingDown = true; });
63 65
64 66 stopThumbnailCacheLoop();
67 stopAuthSessionCleanupLoop();
68 stopShareMaintenanceLoop();
65 69
66 70 // Close DB first so file locks are released as early as possible.
67 71 closeDb();
@@ -121,6 +125,8 @@ function start ()
121 125 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
122 126
123 127 startThumbnailCacheLoop();
128 startAuthSessionCleanupLoop();
129 startShareMaintenanceLoop();
124 130
125 131 // Give the admin route access to the server handle for graceful shutdown.
126 132 app.set('server', httpServer);
@@ -7,6 +7,7 @@ const http = require('http');
7const https = require('https');
7const https = require('https');
8const { initDb, closeDb } = require('./db');
8const { initDb, closeDb } = require('./db');
9const { ensureServerKeys } = require('./crypto');
9const { ensureServerKeys } = require('./crypto');
10const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
10const { loadConfig } = require('./config');
11const { loadConfig } = require('./config');
11const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
12const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
12const { logError } = require('./logger');
13const { logError } = require('./logger');
@@ -14,6 +15,7 @@ const authRoutes = require('./routes/auth');
14const filesRoutes = require('./routes/files');
15const filesRoutes = require('./routes/files');
15const adminRoutes = require('./routes/admin');
16const adminRoutes = require('./routes/admin');
16const shareRoutes = require('./routes/share');
17const shareRoutes = require('./routes/share');
18const { startShareMaintenanceLoop, stopShareMaintenanceLoop } = require('./routes/share');
17
19
18const app = express();
20const app = express();
19
21
@@ -62,6 +64,8 @@ function shutdown (opts = {}, ...servers)
62 active.forEach(s => { s.__isShuttingDown = true; });
64 active.forEach(s => { s.__isShuttingDown = true; });
63
65
64 stopThumbnailCacheLoop();
66 stopThumbnailCacheLoop();
67 stopAuthSessionCleanupLoop();
68 stopShareMaintenanceLoop();
65
69
66 // Close DB first so file locks are released as early as possible.
70 // Close DB first so file locks are released as early as possible.
67 closeDb();
71 closeDb();
@@ -121,6 +125,8 @@ function start ()
121 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
125 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
122
126
123 startThumbnailCacheLoop();
127 startThumbnailCacheLoop();
128 startAuthSessionCleanupLoop();
129 startShareMaintenanceLoop();
124
130
125 // Give the admin route access to the server handle for graceful shutdown.
131 // Give the admin route access to the server handle for graceful shutdown.
126 app.set('server', httpServer);
132 app.set('server', httpServer);
server/routes/share.js +58 −0
@@ -18,6 +18,9 @@ const { logError } = require('../logger');
18 18 const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
19 19 const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
20 20 const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
21 const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
22
23 let shareMaintenanceTimer = null;
21 24
22 25 // ---------------------------------------------------------------------------
23 26 // Helpers
@@ -83,6 +86,56 @@ function ensureZipCacheDir ()
83 86 }
84 87 }
85 88
89 function purgeExpiredShareTokens (opts = {})
90 {
91 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : Date.now();
92 const db = getDb();
93 const result = db.prepare('DELETE FROM share_tokens WHERE expires_at <= ?').run([now]);
94 return Number(result && result.changes || 0);
95 }
96
97 function runShareMaintenanceOnce ()
98 {
99 purgeExpiredShareTokens();
100 pruneZipCache();
101 }
102
103 function startShareMaintenanceLoop ()
104 {
105 if (shareMaintenanceTimer) return;
106
107 try
108 {
109 runShareMaintenanceOnce();
110 } catch
111 {
112 // Ignore startup cleanup failures and continue serving requests.
113 }
114
115 shareMaintenanceTimer = setInterval(() =>
116 {
117 try
118 {
119 runShareMaintenanceOnce();
120 } catch
121 {
122 // Keep serving requests even if periodic maintenance fails.
123 }
124 }, SHARE_MAINTENANCE_INTERVAL_MS);
125
126 if (shareMaintenanceTimer && typeof shareMaintenanceTimer.unref === 'function')
127 {
128 shareMaintenanceTimer.unref();
129 }
130 }
131
132 function stopShareMaintenanceLoop ()
133 {
134 if (!shareMaintenanceTimer) return;
135 clearInterval(shareMaintenanceTimer);
136 shareMaintenanceTimer = null;
137 }
138
86 139 /**
87 140 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
88 141 * Also delete zip files whose corresponding share token has expired.
@@ -655,5 +708,10 @@ function buildShareOpenGraphPage (token, req)
655 708 module.exports = router;
656 709 module.exports.buildZip = buildZip;
657 710 module.exports.pruneZipCache = pruneZipCache;
711 module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
712 module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
713 module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
714 module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
715 module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
658 716 module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
659 717 module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
@@ -18,6 +18,9 @@ const { logError } = require('../logger');
18const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
18const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
19const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
19const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
20const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
20const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
21const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
22
23let shareMaintenanceTimer = null;
21
24
22// ---------------------------------------------------------------------------
25// ---------------------------------------------------------------------------
23// Helpers
26// Helpers
@@ -83,6 +86,56 @@ function ensureZipCacheDir ()
83 }
86 }
84}
87}
85
88
89function purgeExpiredShareTokens (opts = {})
90{
91 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : Date.now();
92 const db = getDb();
93 const result = db.prepare('DELETE FROM share_tokens WHERE expires_at <= ?').run([now]);
94 return Number(result && result.changes || 0);
95}
96
97function runShareMaintenanceOnce ()
98{
99 purgeExpiredShareTokens();
100 pruneZipCache();
101}
102
103function startShareMaintenanceLoop ()
104{
105 if (shareMaintenanceTimer) return;
106
107 try
108 {
109 runShareMaintenanceOnce();
110 } catch
111 {
112 // Ignore startup cleanup failures and continue serving requests.
113 }
114
115 shareMaintenanceTimer = setInterval(() =>
116 {
117 try
118 {
119 runShareMaintenanceOnce();
120 } catch
121 {
122 // Keep serving requests even if periodic maintenance fails.
123 }
124 }, SHARE_MAINTENANCE_INTERVAL_MS);
125
126 if (shareMaintenanceTimer && typeof shareMaintenanceTimer.unref === 'function')
127 {
128 shareMaintenanceTimer.unref();
129 }
130}
131
132function stopShareMaintenanceLoop ()
133{
134 if (!shareMaintenanceTimer) return;
135 clearInterval(shareMaintenanceTimer);
136 shareMaintenanceTimer = null;
137}
138
86/**
139/**
87 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
140 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
88 * Also delete zip files whose corresponding share token has expired.
141 * Also delete zip files whose corresponding share token has expired.
@@ -655,5 +708,10 @@ function buildShareOpenGraphPage (token, req)
655module.exports = router;
708module.exports = router;
656module.exports.buildZip = buildZip;
709module.exports.buildZip = buildZip;
657module.exports.pruneZipCache = pruneZipCache;
710module.exports.pruneZipCache = pruneZipCache;
711module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
712module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
713module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
714module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
715module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
658module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
716module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
659module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
717module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
tests/auth.routes.test.js +43 −1
@@ -52,7 +52,13 @@ jest.mock('../server/db', () =>
52 52 });
53 53
54 54 const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
55 const { SESSION_IDLE_TIMEOUT_MS } = require('../server/auth');
55 const {
56 SESSION_IDLE_TIMEOUT_MS,
57 AUTH_SESSION_REVOKED_RETENTION_MS,
58 AUTH_SESSION_IDLE_RETENTION_MS,
59 purgeStaleSessions,
60 } = require('../server/auth');
61 const { getDb } = require('../server/db');
56 62 const authRoutes = require('../server/routes/auth');
57 63
58 64 jest.setTimeout(30000);
@@ -428,3 +434,39 @@ describe('POST /api/auth/change-password', () =>
428 434 expect(tokenAfterChange.split('.').length).toBe(3);
429 435 });
430 436 });
437
438 describe('auth session cleanup', () =>
439 {
440 test('purges old revoked and idle session rows while keeping fresh rows', () =>
441 {
442 const db = getDb();
443 const now = Date.now();
444 const oldRevokedAt = now - AUTH_SESSION_REVOKED_RETENTION_MS - 5000;
445 const oldIdleSeenAt = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS - 5000;
446 const freshSeenAt = now - 30 * 1000;
447
448 db.prepare(`
449 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
450 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
451 `).run(['stale-revoked', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, now, oldRevokedAt]);
452
453 db.prepare(`
454 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
455 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
456 `).run(['stale-idle', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, oldIdleSeenAt]);
457
458 db.prepare(`
459 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
460 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
461 `).run(['fresh-active', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, freshSeenAt]);
462
463 const purged = purgeStaleSessions({ nowMs: now });
464 expect(purged).toBeGreaterThanOrEqual(2);
465
466 const kept = db.prepare('SELECT session_id FROM auth_sessions ORDER BY session_id').all();
467 const keptIds = kept.map((row) => row.session_id);
468 expect(keptIds).toContain('fresh-active');
469 expect(keptIds).not.toContain('stale-revoked');
470 expect(keptIds).not.toContain('stale-idle');
471 });
472 });
@@ -52,7 +52,13 @@ jest.mock('../server/db', () =>
52});
52});
53
53
54const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
54const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
55const { SESSION_IDLE_TIMEOUT_MS } = require('../server/auth');
55const {
56 SESSION_IDLE_TIMEOUT_MS,
57 AUTH_SESSION_REVOKED_RETENTION_MS,
58 AUTH_SESSION_IDLE_RETENTION_MS,
59 purgeStaleSessions,
60} = require('../server/auth');
61const { getDb } = require('../server/db');
56const authRoutes = require('../server/routes/auth');
62const authRoutes = require('../server/routes/auth');
57
63
58jest.setTimeout(30000);
64jest.setTimeout(30000);
@@ -428,3 +434,39 @@ describe('POST /api/auth/change-password', () =>
428 expect(tokenAfterChange.split('.').length).toBe(3);
434 expect(tokenAfterChange.split('.').length).toBe(3);
429 });
435 });
430});
436});
437
438describe('auth session cleanup', () =>
439{
440 test('purges old revoked and idle session rows while keeping fresh rows', () =>
441 {
442 const db = getDb();
443 const now = Date.now();
444 const oldRevokedAt = now - AUTH_SESSION_REVOKED_RETENTION_MS - 5000;
445 const oldIdleSeenAt = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS - 5000;
446 const freshSeenAt = now - 30 * 1000;
447
448 db.prepare(`
449 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
450 VALUES (?, ?, ?, ?, ?, ?, ?, ?)
451 `).run(['stale-revoked', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, now, oldRevokedAt]);
452
453 db.prepare(`
454 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
455 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
456 `).run(['stale-idle', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, oldIdleSeenAt]);
457
458 db.prepare(`
459 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
460 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
461 `).run(['fresh-active', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, freshSeenAt]);
462
463 const purged = purgeStaleSessions({ nowMs: now });
464 expect(purged).toBeGreaterThanOrEqual(2);
465
466 const kept = db.prepare('SELECT session_id FROM auth_sessions ORDER BY session_id').all();
467 const keptIds = kept.map((row) => row.session_id);
468 expect(keptIds).toContain('fresh-active');
469 expect(keptIds).not.toContain('stale-revoked');
470 expect(keptIds).not.toContain('stale-idle');
471 });
472});
tests/share.routes.test.js +25 −0
@@ -540,6 +540,31 @@ describe('pruneZipCache', () =>
540 540 });
541 541 });
542 542
543 describe('purgeExpiredShareTokens', () =>
544 {
545 test('deletes expired share tokens and keeps valid ones', () =>
546 {
547 const { purgeExpiredShareTokens } = require('../server/routes/share');
548 const db = getDb();
549 const now = Date.now();
550
551 db.prepare(
552 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
553 ).run(['expired-token', '/tmp/old.txt', 0, 'testuser', now - 10000, now - 1000]);
554
555 db.prepare(
556 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
557 ).run(['active-token', '/tmp/new.txt', 0, 'testuser', now - 1000, now + 60000]);
558
559 const removed = purgeExpiredShareTokens({ nowMs: now });
560 expect(removed).toBeGreaterThanOrEqual(1);
561
562 const remaining = db.prepare('SELECT token FROM share_tokens ORDER BY token').all().map((row) => row.token);
563 expect(remaining).toContain('active-token');
564 expect(remaining).not.toContain('expired-token');
565 });
566 });
567
543 568 // ---------------------------------------------------------------------------
544 569 // buildShareOpenGraphPage
545 570 // ---------------------------------------------------------------------------
@@ -540,6 +540,31 @@ describe('pruneZipCache', () =>
540 });
540 });
541});
541});
542
542
543describe('purgeExpiredShareTokens', () =>
544{
545 test('deletes expired share tokens and keeps valid ones', () =>
546 {
547 const { purgeExpiredShareTokens } = require('../server/routes/share');
548 const db = getDb();
549 const now = Date.now();
550
551 db.prepare(
552 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
553 ).run(['expired-token', '/tmp/old.txt', 0, 'testuser', now - 10000, now - 1000]);
554
555 db.prepare(
556 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
557 ).run(['active-token', '/tmp/new.txt', 0, 'testuser', now - 1000, now + 60000]);
558
559 const removed = purgeExpiredShareTokens({ nowMs: now });
560 expect(removed).toBeGreaterThanOrEqual(1);
561
562 const remaining = db.prepare('SELECT token FROM share_tokens ORDER BY token').all().map((row) => row.token);
563 expect(remaining).toContain('active-token');
564 expect(remaining).not.toContain('expired-token');
565 });
566});
567
543// ---------------------------------------------------------------------------
568// ---------------------------------------------------------------------------
544// buildShareOpenGraphPage
569// buildShareOpenGraphPage
545// ---------------------------------------------------------------------------
570// ---------------------------------------------------------------------------