| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const bcrypt = require('bcrypt'); |
| 5 | const router = express.Router(); |
| 6 | |
| 7 | const { getDb } = require('../db'); |
| 8 | const { getServerPublicKeyJwk, hybridDecrypt, hybridEncryptForClient } = require('../crypto'); |
| 9 | const { createToken, requireAuth, revokeSession } = require('../auth'); |
| 10 | |
| 11 | const BCRYPT_ROUNDS = 12; |
| 12 | |
| 13 | function extractCredentials (body) |
| 14 | { |
| 15 | if (body && body.encrypted && body.encrypted.plaintext) |
| 16 | { |
| 17 | return body.encrypted.plaintext; |
| 18 | } |
| 19 | |
| 20 | if (body && body.encrypted) |
| 21 | { |
| 22 | const plain = hybridDecrypt(body.encrypted); |
| 23 | return JSON.parse(plain); |
| 24 | } |
| 25 | |
| 26 | if (body && typeof body.username === 'string' && typeof body.password === 'string') |
| 27 | { |
| 28 | return { username: body.username, password: body.password }; |
| 29 | } |
| 30 | |
| 31 | throw new Error('Invalid payload'); |
| 32 | } |
| 33 | |
| 34 | function makeAuthResponse (token, clientPublicKey) |
| 35 | { |
| 36 | if (clientPublicKey) |
| 37 | { |
| 38 | return { encrypted: hybridEncryptForClient(token, clientPublicKey) }; |
| 39 | } |
| 40 | return { token }; |
| 41 | } |
| 42 | |
| 43 | // --------------------------------------------------------------------------- |
| 44 | // GET /api/auth/server-key |
| 45 | // Returns the server's RSA public key as JWK so the browser can import it. |
| 46 | // --------------------------------------------------------------------------- |
| 47 | router.get('/server-key', (req, res) => |
| 48 | { |
| 49 | res.json({ publicKey: getServerPublicKeyJwk() }); |
| 50 | }); |
| 51 | |
| 52 | // --------------------------------------------------------------------------- |
| 53 | // GET /api/auth/setup-needed |
| 54 | // Returns { needed: true } if no users exist yet. |
| 55 | // --------------------------------------------------------------------------- |
| 56 | router.get('/setup-needed', (req, res) => |
| 57 | { |
| 58 | const db = getDb(); |
| 59 | const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n; |
| 60 | res.json({ needed: count === 0 }); |
| 61 | }); |
| 62 | |
| 63 | // --------------------------------------------------------------------------- |
| 64 | // POST /api/auth/setup |
| 65 | // Creates the first admin account (only when no users exist). |
| 66 | // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey } |
| 67 | // The encrypted payload must be: { username, password } |
| 68 | // --------------------------------------------------------------------------- |
| 69 | router.post('/setup', (req, res) => |
| 70 | { |
| 71 | const db = getDb(); |
| 72 | const count = db.prepare('SELECT COUNT(*) as n FROM users').get().n; |
| 73 | if (count > 0) |
| 74 | { |
| 75 | return res.status(403).json({ error: 'Setup already completed.' }); |
| 76 | } |
| 77 | |
| 78 | let credentials; |
| 79 | try |
| 80 | { |
| 81 | credentials = extractCredentials(req.body); |
| 82 | } catch |
| 83 | { |
| 84 | return res.status(400).json({ error: 'Invalid encrypted payload.' }); |
| 85 | } |
| 86 | |
| 87 | const { username, password } = credentials; |
| 88 | if (!username || !password || username.length < 1 || password.length < 8) |
| 89 | { |
| 90 | return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); |
| 91 | } |
| 92 | |
| 93 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 94 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, 1, ?)').run( |
| 95 | [username, hash, '{}'] |
| 96 | ); |
| 97 | |
| 98 | // Issue token |
| 99 | const token = createToken(username, req, req.body.fingerprint || ''); |
| 100 | res.json(makeAuthResponse(token, req.body.clientPublicKey)); |
| 101 | }); |
| 102 | |
| 103 | // --------------------------------------------------------------------------- |
| 104 | // POST /api/auth/login |
| 105 | // Body: { encrypted: { encryptedKey, iv, ciphertext, tag }, clientPublicKey, fingerprint } |
| 106 | // The encrypted payload must be: { username, password } |
| 107 | // --------------------------------------------------------------------------- |
| 108 | router.post('/login', (req, res) => |
| 109 | { |
| 110 | let credentials; |
| 111 | try |
| 112 | { |
| 113 | credentials = extractCredentials(req.body); |
| 114 | } catch |
| 115 | { |
| 116 | return res.status(400).json({ error: 'Invalid encrypted payload.' }); |
| 117 | } |
| 118 | |
| 119 | const { username, password } = credentials; |
| 120 | if (!username || !password) |
| 121 | { |
| 122 | return res.status(400).json({ error: 'Invalid credentials.' }); |
| 123 | } |
| 124 | |
| 125 | const db = getDb(); |
| 126 | const user = db.prepare('SELECT * FROM users WHERE username = ? COLLATE NOCASE').get([username]); |
| 127 | |
| 128 | if (!user || !bcrypt.compareSync(password, user.password_hash)) |
| 129 | { |
| 130 | return res.status(401).json({ error: 'Invalid credentials.' }); |
| 131 | } |
| 132 | |
| 133 | const fingerprint = req.body.fingerprint || ''; |
| 134 | const token = createToken(user.username, req, fingerprint); |
| 135 | res.json(makeAuthResponse(token, req.body.clientPublicKey)); |
| 136 | }); |
| 137 | |
| 138 | // --------------------------------------------------------------------------- |
| 139 | // GET /api/auth/me |
| 140 | // Returns the current user's basic info. |
| 141 | // --------------------------------------------------------------------------- |
| 142 | router.get('/me', requireAuth, (req, res) => |
| 143 | { |
| 144 | res.json({ |
| 145 | username: req.user.username, |
| 146 | isAdmin: req.user.isAdmin, |
| 147 | permissions: req.user.permissions, |
| 148 | }); |
| 149 | }); |
| 150 | |
| 151 | // --------------------------------------------------------------------------- |
| 152 | // POST /api/auth/logout |
| 153 | // Revokes the active authenticated session token. |
| 154 | // --------------------------------------------------------------------------- |
| 155 | router.post('/logout', requireAuth, (req, res) => |
| 156 | { |
| 157 | revokeSession(req.authSessionId); |
| 158 | res.json({ ok: true }); |
| 159 | }); |
| 160 | |
| 161 | // --------------------------------------------------------------------------- |
| 162 | // POST /api/auth/change-password |
| 163 | // Body: { currentPassword, newPassword } |
| 164 | // --------------------------------------------------------------------------- |
| 165 | router.post('/change-password', requireAuth, (req, res) => |
| 166 | { |
| 167 | const currentPassword = String(req.body && req.body.currentPassword || ''); |
| 168 | const newPassword = String(req.body && req.body.newPassword || ''); |
| 169 | |
| 170 | if (!currentPassword || !newPassword) |
| 171 | { |
| 172 | return res.status(400).json({ error: 'Current and new password are required.' }); |
| 173 | } |
| 174 | |
| 175 | if (newPassword.length < 8) |
| 176 | { |
| 177 | return res.status(400).json({ error: 'New password must be at least 8 characters.' }); |
| 178 | } |
| 179 | |
| 180 | const db = getDb(); |
| 181 | const user = db.prepare('SELECT username, password_hash FROM users WHERE id = ?').get([req.user.id]); |
| 182 | if (!user) |
| 183 | { |
| 184 | return res.status(404).json({ error: 'User not found.' }); |
| 185 | } |
| 186 | |
| 187 | if (!bcrypt.compareSync(currentPassword, user.password_hash)) |
| 188 | { |
| 189 | return res.status(400).json({ error: 'Current password is incorrect.' }); |
| 190 | } |
| 191 | |
| 192 | const nextHash = bcrypt.hashSync(newPassword, BCRYPT_ROUNDS); |
| 193 | db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([nextHash, req.user.id]); |
| 194 | |
| 195 | res.json({ ok: true }); |
| 196 | }); |
| 197 | |
| 198 | module.exports = router; |