Merge fix/uptime-cleanup-guards
@@ -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
@@ -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
---@@ -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');6
const { getDb } = require('./db');6
const { getDb } = require('./db');7
7
8
const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour8
const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour9
const AUTH_SESSION_PURGE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes10
const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours11
const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout12
13
let 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
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_sessions87
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
try100
{101
purgeStaleSessions();102
} catch103
{104
// Ignore purge failures and retry on the next interval.105
}106
107
authSessionPurgeTimer = setInterval(() =>108
{109
try110
{111
purgeStaleSessions();112
} catch113
{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
// Token creation132
// Token creation75
// ---------------------------------------------------------------------------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
};@@ -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');7
const https = require('https');7
const https = require('https');8
const { initDb, closeDb } = require('./db');8
const { initDb, closeDb } = require('./db');9
const { ensureServerKeys } = require('./crypto');9
const { ensureServerKeys } = require('./crypto');10
const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');10
const { loadConfig } = require('./config');11
const { loadConfig } = require('./config');11
const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');12
const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');12
const { logError } = require('./logger');13
const { logError } = require('./logger');@@ -14,6 +15,7 @@ const authRoutes = require('./routes/auth');14
const filesRoutes = require('./routes/files');15
const filesRoutes = require('./routes/files');15
const adminRoutes = require('./routes/admin');16
const adminRoutes = require('./routes/admin');16
const shareRoutes = require('./routes/share');17
const shareRoutes = require('./routes/share');18
const { startShareMaintenanceLoop, stopShareMaintenanceLoop } = require('./routes/share');17
19
18
const app = express();20
const 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);@@ -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
54
const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');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
const authRoutes = require('../server/routes/auth');62
const authRoutes = require('../server/routes/auth');57
63
58
jest.setTimeout(30000);64
jest.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
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
});