| 1 | 'use strict'; |
| 2 | |
| 3 | /** |
| 4 | * Integration tests for the auth routes. |
| 5 | * Spins up an in-memory Express app with a fresh in-memory SQLite database. |
| 6 | */ |
| 7 | |
| 8 | const express = require('express'); |
| 9 | const { once } = require('events'); |
| 10 | const http = require('http'); |
| 11 | const crypto = require('crypto'); |
| 12 | |
| 13 | // ── patch DB to use in-memory database before requiring routes ────────────── |
| 14 | jest.mock('../server/db', () => |
| 15 | { |
| 16 | const { Database } = require('node-sqlite3-wasm'); |
| 17 | let db; |
| 18 | function getDb () |
| 19 | { |
| 20 | if (!db) |
| 21 | { |
| 22 | db = new Database(':memory:'); |
| 23 | db.exec(` |
| 24 | CREATE TABLE IF NOT EXISTS users ( |
| 25 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 26 | username TEXT UNIQUE NOT NULL, |
| 27 | password_hash TEXT NOT NULL, |
| 28 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 29 | permissions TEXT NOT NULL DEFAULT '{}' |
| 30 | ); |
| 31 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 32 | file_path TEXT PRIMARY KEY, |
| 33 | uploader TEXT NOT NULL DEFAULT '', |
| 34 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 35 | ); |
| 36 | CREATE TABLE IF NOT EXISTS auth_sessions ( |
| 37 | session_id TEXT PRIMARY KEY, |
| 38 | username TEXT NOT NULL, |
| 39 | ip TEXT NOT NULL, |
| 40 | region TEXT NOT NULL, |
| 41 | fp_hash TEXT NOT NULL, |
| 42 | created_at INTEGER NOT NULL, |
| 43 | last_seen_at INTEGER NOT NULL, |
| 44 | revoked_at INTEGER |
| 45 | ); |
| 46 | `); |
| 47 | } |
| 48 | return db; |
| 49 | } |
| 50 | function initDb () { getDb(); } |
| 51 | return { getDb, initDb }; |
| 52 | }); |
| 53 | |
| 54 | const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto'); |
| 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'); |
| 62 | const authRoutes = require('../server/routes/auth'); |
| 63 | |
| 64 | jest.setTimeout(30000); |
| 65 | |
| 66 | // ── build minimal app ────────────────────────────────────────────────────── |
| 67 | |
| 68 | let server; |
| 69 | let baseUrl; |
| 70 | |
| 71 | beforeAll(async () => |
| 72 | { |
| 73 | ensureServerKeys(); |
| 74 | const app = express(); |
| 75 | app.use(express.json()); |
| 76 | app.use('/api/auth', authRoutes); |
| 77 | app.use((err, req, res, next) => |
| 78 | { |
| 79 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 80 | }); |
| 81 | server = http.createServer(app); |
| 82 | server.listen(0); |
| 83 | await once(server, 'listening'); |
| 84 | const port = server.address().port; |
| 85 | baseUrl = `http://127.0.0.1:${port}`; |
| 86 | }); |
| 87 | |
| 88 | afterAll(() => server.close()); |
| 89 | |
| 90 | // ── helpers ──────────────────────────────────────────────────────────────── |
| 91 | |
| 92 | function get (path) |
| 93 | { |
| 94 | return new Promise((resolve, reject) => |
| 95 | { |
| 96 | http.get(baseUrl + path, res => |
| 97 | { |
| 98 | let body = ''; |
| 99 | res.on('data', d => body += d); |
| 100 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); |
| 101 | }).on('error', reject); |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | function post (path, data) |
| 106 | { |
| 107 | const payload = JSON.stringify(data); |
| 108 | return new Promise((resolve, reject) => |
| 109 | { |
| 110 | const req = http.request(baseUrl + path, { |
| 111 | method: 'POST', |
| 112 | headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }, |
| 113 | }, res => |
| 114 | { |
| 115 | let body = ''; |
| 116 | res.on('data', d => body += d); |
| 117 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); |
| 118 | }); |
| 119 | req.on('error', reject); |
| 120 | req.write(payload); |
| 121 | req.end(); |
| 122 | }); |
| 123 | } |
| 124 | |
| 125 | function authed (method, path, token, fingerprint, data) |
| 126 | { |
| 127 | const payload = data ? JSON.stringify(data) : undefined; |
| 128 | return new Promise((resolve, reject) => |
| 129 | { |
| 130 | const req = http.request(baseUrl + path, { |
| 131 | method, |
| 132 | headers: { |
| 133 | Authorization: `Bearer ${token}`, |
| 134 | 'X-Fp': fingerprint, |
| 135 | 'Content-Type': 'application/json', |
| 136 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 137 | }, |
| 138 | }, res => |
| 139 | { |
| 140 | let body = ''; |
| 141 | res.on('data', d => body += d); |
| 142 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); |
| 143 | }); |
| 144 | req.on('error', reject); |
| 145 | if (payload) req.write(payload); |
| 146 | req.end(); |
| 147 | }); |
| 148 | } |
| 149 | |
| 150 | /** Simulate the client-side hybrid encrypt targeting the server public key. */ |
| 151 | function clientEncrypt (obj) |
| 152 | { |
| 153 | const jwk = getServerPublicKeyJwk(); |
| 154 | const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' }); |
| 155 | const plain = JSON.stringify(obj); |
| 156 | const aesKey = crypto.randomBytes(32); |
| 157 | const iv = crypto.randomBytes(12); |
| 158 | const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv); |
| 159 | const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); |
| 160 | const tag = cipher.getAuthTag(); |
| 161 | const ek = crypto.publicEncrypt( |
| 162 | { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, |
| 163 | aesKey, |
| 164 | ); |
| 165 | return { |
| 166 | encryptedKey: ek.toString('base64'), |
| 167 | iv: iv.toString('base64'), |
| 168 | ciphertext: ct.toString('base64'), |
| 169 | tag: tag.toString('base64'), |
| 170 | }; |
| 171 | } |
| 172 | |
| 173 | /** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */ |
| 174 | function makeClientKeyPair () |
| 175 | { |
| 176 | const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { |
| 177 | modulusLength: 2048, |
| 178 | publicKeyEncoding: { type: 'spki', format: 'pem' }, |
| 179 | privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, |
| 180 | }); |
| 181 | const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' }); |
| 182 | return { privateKey, publicKeyJwk }; |
| 183 | } |
| 184 | |
| 185 | /** Decrypt the token the server sends back. */ |
| 186 | function clientDecrypt (payload, privateKey) |
| 187 | { |
| 188 | const ek = Buffer.from(payload.encryptedKey, 'base64'); |
| 189 | const iv = Buffer.from(payload.iv, 'base64'); |
| 190 | const ct = Buffer.from(payload.ciphertext, 'base64'); |
| 191 | const tg = Buffer.from(payload.tag, 'base64'); |
| 192 | const rawAes = crypto.privateDecrypt( |
| 193 | { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, |
| 194 | ek, |
| 195 | ); |
| 196 | const decipher = crypto.createDecipheriv('aes-256-gcm', rawAes, iv); |
| 197 | decipher.setAuthTag(tg); |
| 198 | return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); |
| 199 | } |
| 200 | |
| 201 | // ── tests ────────────────────────────────────────────────────────────────── |
| 202 | |
| 203 | describe('GET /api/auth/server-key', () => |
| 204 | { |
| 205 | test('returns a JWK public key', async () => |
| 206 | { |
| 207 | const { status, body } = await get('/api/auth/server-key'); |
| 208 | expect(status).toBe(200); |
| 209 | expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) }); |
| 210 | }); |
| 211 | }); |
| 212 | |
| 213 | describe('GET /api/auth/setup-needed', () => |
| 214 | { |
| 215 | test('returns needed=true when no users exist', async () => |
| 216 | { |
| 217 | const { status, body } = await get('/api/auth/setup-needed'); |
| 218 | expect(status).toBe(200); |
| 219 | expect(body.needed).toBe(true); |
| 220 | }); |
| 221 | }); |
| 222 | |
| 223 | describe('POST /api/auth/setup', () => |
| 224 | { |
| 225 | let kp; |
| 226 | |
| 227 | beforeAll(() => { kp = makeClientKeyPair(); }); |
| 228 | |
| 229 | test('rejects weak password', async () => |
| 230 | { |
| 231 | const encrypted = clientEncrypt({ username: 'admin', password: 'short' }); |
| 232 | const { status, body } = await post('/api/auth/setup', { |
| 233 | encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', |
| 234 | }); |
| 235 | expect(status).toBe(400); |
| 236 | }); |
| 237 | |
| 238 | test('creates admin and returns encrypted token', async () => |
| 239 | { |
| 240 | const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); |
| 241 | const { status, body } = await post('/api/auth/setup', { |
| 242 | encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', |
| 243 | }); |
| 244 | expect(status).toBe(200); |
| 245 | expect(body.encrypted).toMatchObject({ |
| 246 | encryptedKey: expect.any(String), |
| 247 | iv: expect.any(String), |
| 248 | ciphertext: expect.any(String), |
| 249 | tag: expect.any(String), |
| 250 | }); |
| 251 | |
| 252 | // Token should be a valid JWT string |
| 253 | const token = clientDecrypt(body.encrypted, kp.privateKey); |
| 254 | expect(token.split('.').length).toBe(3); |
| 255 | }); |
| 256 | |
| 257 | test('setup-needed is now false', async () => |
| 258 | { |
| 259 | const { body } = await get('/api/auth/setup-needed'); |
| 260 | expect(body.needed).toBe(false); |
| 261 | }); |
| 262 | |
| 263 | test('cannot run setup again once a user exists', async () => |
| 264 | { |
| 265 | const kp2 = makeClientKeyPair(); |
| 266 | const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' }); |
| 267 | const { status } = await post('/api/auth/setup', { |
| 268 | encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test', |
| 269 | }); |
| 270 | expect(status).toBe(403); |
| 271 | }); |
| 272 | }); |
| 273 | |
| 274 | describe('POST /api/auth/login', () => |
| 275 | { |
| 276 | let kp; |
| 277 | beforeAll(() => { kp = makeClientKeyPair(); }); |
| 278 | |
| 279 | test('rejects wrong password', async () => |
| 280 | { |
| 281 | const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' }); |
| 282 | const { status } = await post('/api/auth/login', { |
| 283 | encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', |
| 284 | }); |
| 285 | expect(status).toBe(401); |
| 286 | }); |
| 287 | |
| 288 | test('returns encrypted token on correct credentials', async () => |
| 289 | { |
| 290 | const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); |
| 291 | const { status, body } = await post('/api/auth/login', { |
| 292 | encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', |
| 293 | }); |
| 294 | expect(status).toBe(200); |
| 295 | const token = clientDecrypt(body.encrypted, kp.privateKey); |
| 296 | expect(token.split('.').length).toBe(3); |
| 297 | }); |
| 298 | |
| 299 | test('accepts login username in different case', async () => |
| 300 | { |
| 301 | const encrypted = clientEncrypt({ username: 'AdMiN', password: 'adminpass1' }); |
| 302 | const { status, body } = await post('/api/auth/login', { |
| 303 | encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', |
| 304 | }); |
| 305 | expect(status).toBe(200); |
| 306 | const token = clientDecrypt(body.encrypted, kp.privateKey); |
| 307 | expect(token.split('.').length).toBe(3); |
| 308 | }); |
| 309 | |
| 310 | test('rejects invalid encrypted payload', async () => |
| 311 | { |
| 312 | const { status } = await post('/api/auth/login', { |
| 313 | encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' }, |
| 314 | clientPublicKey: kp.publicKeyJwk, |
| 315 | fingerprint: 'test', |
| 316 | }); |
| 317 | expect(status).toBe(400); |
| 318 | }); |
| 319 | }); |
| 320 | |
| 321 | describe('session lifecycle', () => |
| 322 | { |
| 323 | const fingerprint = 'test'; |
| 324 | |
| 325 | async function loginAndGetToken () |
| 326 | { |
| 327 | const kp = makeClientKeyPair(); |
| 328 | const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); |
| 329 | const { status, body } = await post('/api/auth/login', { |
| 330 | encrypted, |
| 331 | clientPublicKey: kp.publicKeyJwk, |
| 332 | fingerprint, |
| 333 | }); |
| 334 | expect(status).toBe(200); |
| 335 | return clientDecrypt(body.encrypted, kp.privateKey); |
| 336 | } |
| 337 | |
| 338 | test('POST /api/auth/logout revokes active session', async () => |
| 339 | { |
| 340 | const token = await loginAndGetToken(); |
| 341 | |
| 342 | const meBefore = await authed('GET', '/api/auth/me', token, fingerprint); |
| 343 | expect(meBefore.status).toBe(200); |
| 344 | |
| 345 | const logout = await authed('POST', '/api/auth/logout', token, fingerprint, {}); |
| 346 | expect(logout.status).toBe(200); |
| 347 | expect(logout.body.ok).toBe(true); |
| 348 | |
| 349 | const meAfter = await authed('GET', '/api/auth/me', token, fingerprint); |
| 350 | expect(meAfter.status).toBe(401); |
| 351 | }); |
| 352 | |
| 353 | test('session expires after 1 hour of inactivity', async () => |
| 354 | { |
| 355 | const token = await loginAndGetToken(); |
| 356 | |
| 357 | const meBefore = await authed('GET', '/api/auth/me', token, fingerprint); |
| 358 | expect(meBefore.status).toBe(200); |
| 359 | |
| 360 | const realNow = Date.now; |
| 361 | try |
| 362 | { |
| 363 | const jumped = realNow() + SESSION_IDLE_TIMEOUT_MS + 1000; |
| 364 | Date.now = jest.fn(() => jumped); |
| 365 | |
| 366 | const meAfter = await authed('GET', '/api/auth/me', token, fingerprint); |
| 367 | expect(meAfter.status).toBe(401); |
| 368 | } finally |
| 369 | { |
| 370 | Date.now = realNow; |
| 371 | } |
| 372 | }); |
| 373 | }); |
| 374 | |
| 375 | describe('POST /api/auth/change-password', () => |
| 376 | { |
| 377 | const fingerprint = 'test'; |
| 378 | |
| 379 | async function loginAndGetToken (password) |
| 380 | { |
| 381 | const kp = makeClientKeyPair(); |
| 382 | const encrypted = clientEncrypt({ username: 'admin', password }); |
| 383 | const { status, body } = await post('/api/auth/login', { |
| 384 | encrypted, |
| 385 | clientPublicKey: kp.publicKeyJwk, |
| 386 | fingerprint, |
| 387 | }); |
| 388 | expect(status).toBe(200); |
| 389 | return clientDecrypt(body.encrypted, kp.privateKey); |
| 390 | } |
| 391 | |
| 392 | test('rejects incorrect current password', async () => |
| 393 | { |
| 394 | const token = await loginAndGetToken('adminpass1'); |
| 395 | const res = await authed('POST', '/api/auth/change-password', token, fingerprint, { |
| 396 | currentPassword: 'wrong-pass', |
| 397 | newPassword: 'adminpass2', |
| 398 | }); |
| 399 | |
| 400 | expect(res.status).toBe(400); |
| 401 | expect(res.body.error).toMatch(/current password is incorrect/i); |
| 402 | }); |
| 403 | |
| 404 | test('updates password and invalidates old login credentials', async () => |
| 405 | { |
| 406 | const token = await loginAndGetToken('adminpass1'); |
| 407 | |
| 408 | const change = await authed('POST', '/api/auth/change-password', token, fingerprint, { |
| 409 | currentPassword: 'adminpass1', |
| 410 | newPassword: 'adminpass2', |
| 411 | }); |
| 412 | expect(change.status).toBe(200); |
| 413 | expect(change.body.ok).toBe(true); |
| 414 | |
| 415 | const oldLoginEncrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); |
| 416 | const oldLoginKp = makeClientKeyPair(); |
| 417 | const oldLogin = await post('/api/auth/login', { |
| 418 | encrypted: oldLoginEncrypted, |
| 419 | clientPublicKey: oldLoginKp.publicKeyJwk, |
| 420 | fingerprint, |
| 421 | }); |
| 422 | expect(oldLogin.status).toBe(401); |
| 423 | |
| 424 | const newLoginEncrypted = clientEncrypt({ username: 'admin', password: 'adminpass2' }); |
| 425 | const newLoginKp = makeClientKeyPair(); |
| 426 | const newLogin = await post('/api/auth/login', { |
| 427 | encrypted: newLoginEncrypted, |
| 428 | clientPublicKey: newLoginKp.publicKeyJwk, |
| 429 | fingerprint, |
| 430 | }); |
| 431 | expect(newLogin.status).toBe(200); |
| 432 | |
| 433 | const tokenAfterChange = clientDecrypt(newLogin.body.encrypted, newLoginKp.privateKey); |
| 434 | expect(tokenAfterChange.split('.').length).toBe(3); |
| 435 | }); |
| 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 | }); |