'use strict'; /** * Integration tests for the auth routes. * Spins up an in-memory Express app with a fresh in-memory SQLite database. */ const express = require('express'); const { once } = require('events'); const http = require('http'); const crypto = require('crypto'); // ── patch DB to use in-memory database before requiring routes ────────────── jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; function getDb () { if (!db) { db = new Database(':memory:'); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]' ); CREATE TABLE IF NOT EXISTS auth_sessions ( session_id TEXT PRIMARY KEY, username TEXT NOT NULL, ip TEXT NOT NULL, region TEXT NOT NULL, fp_hash TEXT NOT NULL, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, revoked_at INTEGER ); `); } return db; } function initDb () { getDb(); } return { getDb, initDb }; }); const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto'); const { SESSION_IDLE_TIMEOUT_MS, AUTH_SESSION_REVOKED_RETENTION_MS, AUTH_SESSION_IDLE_RETENTION_MS, purgeStaleSessions, } = require('../server/auth'); const { getDb } = require('../server/db'); const authRoutes = require('../server/routes/auth'); jest.setTimeout(30000); // ── build minimal app ────────────────────────────────────────────────────── let server; let baseUrl; beforeAll(async () => { ensureServerKeys(); const app = express(); app.use(express.json()); app.use('/api/auth', authRoutes); app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: err.message || 'Internal error' }); }); server = http.createServer(app); server.listen(0); await once(server, 'listening'); const port = server.address().port; baseUrl = `http://127.0.0.1:${port}`; }); afterAll(() => server.close()); // ── helpers ──────────────────────────────────────────────────────────────── function get (path) { return new Promise((resolve, reject) => { http.get(baseUrl + path, res => { let body = ''; res.on('data', d => body += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); }).on('error', reject); }); } function post (path, data) { const payload = JSON.stringify(data); return new Promise((resolve, reject) => { const req = http.request(baseUrl + path, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }, }, res => { let body = ''; res.on('data', d => body += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); }); req.on('error', reject); req.write(payload); req.end(); }); } function authed (method, path, token, fingerprint, data) { const payload = data ? JSON.stringify(data) : undefined; return new Promise((resolve, reject) => { const req = http.request(baseUrl + path, { method, headers: { Authorization: `Bearer ${token}`, 'X-Fp': fingerprint, 'Content-Type': 'application/json', ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), }, }, res => { let body = ''; res.on('data', d => body += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) })); }); req.on('error', reject); if (payload) req.write(payload); req.end(); }); } /** Simulate the client-side hybrid encrypt targeting the server public key. */ function clientEncrypt (obj) { const jwk = getServerPublicKeyJwk(); const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' }); const plain = JSON.stringify(obj); const aesKey = crypto.randomBytes(32); const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv); const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); const ek = crypto.publicEncrypt( { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, aesKey, ); return { encryptedKey: ek.toString('base64'), iv: iv.toString('base64'), ciphertext: ct.toString('base64'), tag: tag.toString('base64'), }; } /** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */ function makeClientKeyPair () { const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' }); return { privateKey, publicKeyJwk }; } /** Decrypt the token the server sends back. */ function clientDecrypt (payload, privateKey) { const ek = Buffer.from(payload.encryptedKey, 'base64'); const iv = Buffer.from(payload.iv, 'base64'); const ct = Buffer.from(payload.ciphertext, 'base64'); const tg = Buffer.from(payload.tag, 'base64'); const rawAes = crypto.privateDecrypt( { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' }, ek, ); const decipher = crypto.createDecipheriv('aes-256-gcm', rawAes, iv); decipher.setAuthTag(tg); return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); } // ── tests ────────────────────────────────────────────────────────────────── describe('GET /api/auth/server-key', () => { test('returns a JWK public key', async () => { const { status, body } = await get('/api/auth/server-key'); expect(status).toBe(200); expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) }); }); }); describe('GET /api/auth/setup-needed', () => { test('returns needed=true when no users exist', async () => { const { status, body } = await get('/api/auth/setup-needed'); expect(status).toBe(200); expect(body.needed).toBe(true); }); }); describe('POST /api/auth/setup', () => { let kp; beforeAll(() => { kp = makeClientKeyPair(); }); test('rejects weak password', async () => { const encrypted = clientEncrypt({ username: 'admin', password: 'short' }); const { status, body } = await post('/api/auth/setup', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(400); }); test('creates admin and returns encrypted token', async () => { const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); const { status, body } = await post('/api/auth/setup', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(200); expect(body.encrypted).toMatchObject({ encryptedKey: expect.any(String), iv: expect.any(String), ciphertext: expect.any(String), tag: expect.any(String), }); // Token should be a valid JWT string const token = clientDecrypt(body.encrypted, kp.privateKey); expect(token.split('.').length).toBe(3); }); test('setup-needed is now false', async () => { const { body } = await get('/api/auth/setup-needed'); expect(body.needed).toBe(false); }); test('cannot run setup again once a user exists', async () => { const kp2 = makeClientKeyPair(); const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' }); const { status } = await post('/api/auth/setup', { encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(403); }); }); describe('POST /api/auth/login', () => { let kp; beforeAll(() => { kp = makeClientKeyPair(); }); test('rejects wrong password', async () => { const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' }); const { status } = await post('/api/auth/login', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(401); }); test('returns encrypted token on correct credentials', async () => { const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); const { status, body } = await post('/api/auth/login', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(200); const token = clientDecrypt(body.encrypted, kp.privateKey); expect(token.split('.').length).toBe(3); }); test('accepts login username in different case', async () => { const encrypted = clientEncrypt({ username: 'AdMiN', password: 'adminpass1' }); const { status, body } = await post('/api/auth/login', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(200); const token = clientDecrypt(body.encrypted, kp.privateKey); expect(token.split('.').length).toBe(3); }); test('rejects invalid encrypted payload', async () => { const { status } = await post('/api/auth/login', { encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' }, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test', }); expect(status).toBe(400); }); }); describe('session lifecycle', () => { const fingerprint = 'test'; async function loginAndGetToken () { const kp = makeClientKeyPair(); const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); const { status, body } = await post('/api/auth/login', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint, }); expect(status).toBe(200); return clientDecrypt(body.encrypted, kp.privateKey); } test('POST /api/auth/logout revokes active session', async () => { const token = await loginAndGetToken(); const meBefore = await authed('GET', '/api/auth/me', token, fingerprint); expect(meBefore.status).toBe(200); const logout = await authed('POST', '/api/auth/logout', token, fingerprint, {}); expect(logout.status).toBe(200); expect(logout.body.ok).toBe(true); const meAfter = await authed('GET', '/api/auth/me', token, fingerprint); expect(meAfter.status).toBe(401); }); test('session expires after 1 hour of inactivity', async () => { const token = await loginAndGetToken(); const meBefore = await authed('GET', '/api/auth/me', token, fingerprint); expect(meBefore.status).toBe(200); const realNow = Date.now; try { const jumped = realNow() + SESSION_IDLE_TIMEOUT_MS + 1000; Date.now = jest.fn(() => jumped); const meAfter = await authed('GET', '/api/auth/me', token, fingerprint); expect(meAfter.status).toBe(401); } finally { Date.now = realNow; } }); }); describe('POST /api/auth/change-password', () => { const fingerprint = 'test'; async function loginAndGetToken (password) { const kp = makeClientKeyPair(); const encrypted = clientEncrypt({ username: 'admin', password }); const { status, body } = await post('/api/auth/login', { encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint, }); expect(status).toBe(200); return clientDecrypt(body.encrypted, kp.privateKey); } test('rejects incorrect current password', async () => { const token = await loginAndGetToken('adminpass1'); const res = await authed('POST', '/api/auth/change-password', token, fingerprint, { currentPassword: 'wrong-pass', newPassword: 'adminpass2', }); expect(res.status).toBe(400); expect(res.body.error).toMatch(/current password is incorrect/i); }); test('updates password and invalidates old login credentials', async () => { const token = await loginAndGetToken('adminpass1'); const change = await authed('POST', '/api/auth/change-password', token, fingerprint, { currentPassword: 'adminpass1', newPassword: 'adminpass2', }); expect(change.status).toBe(200); expect(change.body.ok).toBe(true); const oldLoginEncrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' }); const oldLoginKp = makeClientKeyPair(); const oldLogin = await post('/api/auth/login', { encrypted: oldLoginEncrypted, clientPublicKey: oldLoginKp.publicKeyJwk, fingerprint, }); expect(oldLogin.status).toBe(401); const newLoginEncrypted = clientEncrypt({ username: 'admin', password: 'adminpass2' }); const newLoginKp = makeClientKeyPair(); const newLogin = await post('/api/auth/login', { encrypted: newLoginEncrypted, clientPublicKey: newLoginKp.publicKeyJwk, fingerprint, }); expect(newLogin.status).toBe(200); const tokenAfterChange = clientDecrypt(newLogin.body.encrypted, newLoginKp.privateKey); expect(tokenAfterChange.split('.').length).toBe(3); }); }); describe('auth session cleanup', () => { test('purges old revoked and idle session rows while keeping fresh rows', () => { const db = getDb(); const now = Date.now(); const oldRevokedAt = now - AUTH_SESSION_REVOKED_RETENTION_MS - 5000; const oldIdleSeenAt = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS - 5000; const freshSeenAt = now - 30 * 1000; db.prepare(` INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) `).run(['stale-revoked', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, now, oldRevokedAt]); db.prepare(` INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL) `).run(['stale-idle', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, oldIdleSeenAt]); db.prepare(` INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL) `).run(['fresh-active', 'admin', '127.0.0.1', 'local:127.0.0.1', 'fp', now, freshSeenAt]); const purged = purgeStaleSessions({ nowMs: now }); expect(purged).toBeGreaterThanOrEqual(2); const kept = db.prepare('SELECT session_id FROM auth_sessions ORDER BY session_id').all(); const keptIds = kept.map((row) => row.session_id); expect(keptIds).toContain('fresh-active'); expect(keptIds).not.toContain('stale-revoked'); expect(keptIds).not.toContain('stale-idle'); }); });