'use strict'; const express = require('express'); const bcrypt = require('bcrypt'); const router = express.Router(); const { getDb } = require('../db'); const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto'); const { createToken, requireAuth, revokeSession } = require('../auth'); const BCRYPT_ROUNDS = 12; function extractCredentials (body) { if (body && body.encrypted && body.encrypted.plaintext) { return body.encrypted.plaintext; } if (body && body.encrypted) { const plain = hybridDecrypt(body.encrypted); return JSON.parse(plain); } if (body && typeof body.username === 'string' && typeof body.password === 'string') { return { username: body.username, password: body.password }; } throw new Error('Invalid payload'); } function makeAuthResponse (token, clientPublicKey) { if (clientPublicKey) { return { encrypted: hybridEncryptForClient(token, clientPublicKey) }; } return { token }; } // --------------------------------------------------------------------------- // GET /api/auth/server-key // Returns the server's RSA public key as JWK so the browser can import it. // --------------------------------------------------------------------------- router.get('/server-key', (req, res) => { res.json({ publicKey: getServerPublicKeyJwk() }); }); // --------------------------------------------------------------------------- // GET /api/auth/setup-needed // Returns { needed: true } if no users exist yet. // --------------------------------------------------------------------------- router.get('/setup-needed', (req, res) => { const db = getDb(); const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n; res.json({ needed: count === 0 }); }); // --------------------------------------------------------------------------- // POST /api/auth/setup // Creates the first admin account (only when no users exist). // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey } // The encrypted payload must be: { username, password } // --------------------------------------------------------------------------- router.post('/setup', (req, res) => { const db = getDb(); const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n; if (count > 0) { return res.status(403).json({ error: 'Setup already completed.' }); } let credentials; try { credentials = extractCredentials(req.body); } catch { return res.status(400).json({ error: 'Invalid encrypted payload.' }); } const { username, password } = credentials; if (!username || !password || username.length < 1 || password.length < 8) { return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); } const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run( [username, hash, '{}'] ); // Issue token const token = createToken(username, req, req.body.fingerprint || ''); res.json(makeAuthResponse(token, req.body.clientPublicKey)); }); // --------------------------------------------------------------------------- // POST /api/auth/login // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint } // The encrypted payload must be: { username, password } // --------------------------------------------------------------------------- router.post('/login', (req, res) => { let credentials; try { credentials = extractCredentials(req.body); } catch { return res.status(400).json({ error: 'Invalid encrypted payload.' }); } const { username, password } = credentials; if (!username || !password) { return res.status(400).json({ error: 'Invalid credentials.' }); } const db = getDb(); const user = db.prepare('SELECT * FROM users WHERE username = ? COLLATE NOCASE').get([username]); if (!user || !bcrypt.compareSync(password, user.password_hash)) { return res.status(401).json({ error: 'Invalid credentials.' }); } const fingerprint = req.body.fingerprint || ''; const token = createToken(user.username, req, fingerprint); res.json(makeAuthResponse(token, req.body.clientPublicKey)); }); // --------------------------------------------------------------------------- // GET /api/auth/me // Returns the current user's basic info. // --------------------------------------------------------------------------- router.get('/me', requireAuth, (req, res) => { res.json({ username: req.user.username, isAdmin: req.user.isAdmin, permissions: req.user.permissions, }); }); // --------------------------------------------------------------------------- // POST /api/auth/logout // Revokes the active authenticated session token. // --------------------------------------------------------------------------- router.post('/logout', requireAuth, (req, res) => { revokeSession(req.authSessionId); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // POST /api/auth/change-password // Body: { currentPassword, newPassword } // --------------------------------------------------------------------------- router.post('/change-password', requireAuth, (req, res) => { const currentPassword = String(req.body && req.body.currentPassword || ''); const newPassword = String(req.body && req.body.newPassword || ''); if (!currentPassword || !newPassword) { return res.status(400).json({ error: 'Current and new password are required.' }); } if (newPassword.length < 8) { return res.status(400).json({ error: 'New password must be at least 8 characters.' }); } const db = getDb(); const user = db.prepare('SELECT username, password_hash FROM users WHERE id = ?').get([req.user.id]); if (!user) { return res.status(404).json({ error: 'User not found.' }); } if (!bcrypt.compareSync(currentPassword, user.password_hash)) { return res.status(400).json({ error: 'Current password is incorrect.' }); } const nextHash = bcrypt.hashSync(newPassword, BCRYPT_ROUNDS); db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([nextHash, req.user.id]); res.json({ ok: true }); }); module.exports = router;