A modern, self-hosted backup solution for secure, encrypted backups across local and cloud storage.
feat: adds password hashing for harden security
towfiqifed43a2fe3c7
diff --git a/backend/__tests__/controllers/UserController.test.ts b/backend/__tests__/controllers/UserController.test.tsindex f4f7e5f..7f3f9da 100644--- a/backend/__tests__/controllers/UserController.test.ts+++ b/backend/__tests__/controllers/UserController.test.ts@@ -4,6 +4,10 @@ import { configService } from '../../src/services/ConfigService';import jwt from 'jsonwebtoken';jest.mock('jsonwebtoken');++const mockVerifyPassword = jest.fn();+const mockHashAndStorePassword = jest.fn();+jest.mock('../../src/services/ConfigService', () => ({configService: {config: {@@ -12,6 +16,8 @@ jest.mock('../../src/services/ConfigService', () => ({SECRET: 'test-secret',SESSION_DURATION: 7,},+ verifyPassword: (...args: any[]) => mockVerifyPassword(...args),+ hashAndStorePassword: (...args: any[]) => mockHashAndStorePassword(...args),},}));@@ -26,6 +32,8 @@ describe('UserController', () => {beforeEach(() => {jest.clearAllMocks();+ mockVerifyPassword.mockReturnValue(false);+ mockHashAndStorePassword.mockReturnValue('$2a$10$mockhash');mockJson = jest.fn().mockReturnThis();mockStatus = jest.fn().mockReturnValue({ json: mockJson });@@ -76,33 +84,45 @@ describe('UserController', () => {it('should return 401 if username is incorrect', async () => {mockRequest.body = { username: 'wronguser', password: 'testpass' };+ mockVerifyPassword.mockReturnValue(true);await userController.loginUser(mockRequest as Request, mockResponse as Response);expect(mockStatus).toHaveBeenCalledWith(401);- expect(mockJson).toHaveBeenCalledWith({ success: false, error: 'Incorrect Username' });+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ error: 'Incorrect Username or Password',+ });});it('should return 401 if password is incorrect', async () => {mockRequest.body = { username: 'testuser', password: 'wrongpass' };+ mockVerifyPassword.mockReturnValue(false);await userController.loginUser(mockRequest as Request, mockResponse as Response);expect(mockStatus).toHaveBeenCalledWith(401);- expect(mockJson).toHaveBeenCalledWith({ success: false, error: 'Incorrect Password' });+ expect(mockJson).toHaveBeenCalledWith({+ success: false,+ error: 'Incorrect Username or Password',+ });});it('should successfully login with correct credentials', async () => {mockRequest.body = { username: 'testuser', password: 'testpass' };+ mockVerifyPassword.mockReturnValue(true);(jwt.sign as jest.Mock).mockReturnValue('mock-token');await userController.loginUser(mockRequest as Request, mockResponse as Response);- expect(jwt.sign).toHaveBeenCalledWith({ user: 'testuser' }, 'test-secret');+ expect(jwt.sign).toHaveBeenCalledWith({ user: 'testuser' }, 'test-secret', {+ expiresIn: '7d',+ });expect(mockCookie).toHaveBeenCalledWith('token', 'mock-token', {httpOnly: true,sameSite: 'lax',maxAge: 7 * 24 * 60 * 60 * 1000,+ secure: undefined,});expect(mockStatus).toHaveBeenCalledWith(200);expect(mockJson).toHaveBeenCalledWith({ success: true, error: null });@@ -113,6 +133,7 @@ describe('UserController', () => {(configService.config as any).SESSION_DURATION = undefined;mockRequest.body = { username: 'testuser', password: 'testpass' };+ mockVerifyPassword.mockReturnValue(true);(jwt.sign as jest.Mock).mockReturnValue('mock-token');await userController.loginUser(mockRequest as Request, mockResponse as Response);@@ -121,6 +142,7 @@ describe('UserController', () => {httpOnly: true,sameSite: 'lax',maxAge: 7 * 24 * 60 * 60 * 1000,+ secure: undefined,});(configService.config as any).SESSION_DURATION = originalDuration;diff --git a/backend/__tests__/routes/users.test.ts b/backend/__tests__/routes/users.test.tsindex dd76db3..b5c8332 100644--- a/backend/__tests__/routes/users.test.ts+++ b/backend/__tests__/routes/users.test.ts@@ -8,6 +8,10 @@ import Cookies from 'cookies';jest.mock('jsonwebtoken');jest.mock('cookies');++const mockVerifyPassword = jest.fn();+const mockHashAndStorePassword = jest.fn();+jest.mock('../../src/services/ConfigService', () => ({configService: {config: {@@ -16,6 +20,8 @@ jest.mock('../../src/services/ConfigService', () => ({SECRET: 'test-secret',SESSION_DURATION: 7,},+ verifyPassword: (...args: any[]) => mockVerifyPassword(...args),+ hashAndStorePassword: (...args: any[]) => mockHashAndStorePassword(...args),},}));@@ -25,6 +31,8 @@ describe('User Routes', () => {beforeEach(() => {jest.clearAllMocks();+ mockVerifyPassword.mockReturnValue(false);+ mockHashAndStorePassword.mockReturnValue('$2a$10$mockhash');userController = new UserController();app = express();@@ -48,25 +56,28 @@ describe('User Routes', () => {});it('should return 401 if username is incorrect', async () => {+ mockVerifyPassword.mockReturnValue(true);const response = await request(app).post('/api/user/login').send({ username: 'wronguser', password: 'testpass' });expect(response.status).toBe(401);- expect(response.body).toEqual({ success: false, error: 'Incorrect Username' });+ expect(response.body).toEqual({ success: false, error: 'Incorrect Username or Password' });});it('should return 401 if password is incorrect', async () => {+ mockVerifyPassword.mockReturnValue(false);const response = await request(app).post('/api/user/login').send({ username: 'testuser', password: 'wrongpass' });expect(response.status).toBe(401);- expect(response.body).toEqual({ success: false, error: 'Incorrect Password' });+ expect(response.body).toEqual({ success: false, error: 'Incorrect Username or Password' });});it('should successfully login with correct credentials', async () => {(jwt.sign as jest.Mock).mockReturnValue('mock-token');+ mockVerifyPassword.mockReturnValue(true);const response = await request(app).post('/api/user/login')@@ -74,7 +85,9 @@ describe('User Routes', () => {expect(response.status).toBe(200);expect(response.body).toEqual({ success: true, error: null });- expect(jwt.sign).toHaveBeenCalledWith({ user: 'testuser' }, 'test-secret');+ expect(jwt.sign).toHaveBeenCalledWith({ user: 'testuser' }, 'test-secret', {+ expiresIn: '7d',+ });});});diff --git a/backend/package.json b/backend/package.jsonindex b5910b4..9647baf 100644--- a/backend/package.json+++ b/backend/package.json@@ -15,6 +15,7 @@],"dependencies": {"@napi-rs/keyring": "^1.2.0",+ "bcryptjs": "^3.0.3","better-sqlite3": "12.2.0","cookies": "^0.9.1","cors": "^2.8.5",diff --git a/backend/src/controllers/UserController.ts b/backend/src/controllers/UserController.tsindex 3fc2f10..b21c51f 100644--- a/backend/src/controllers/UserController.ts+++ b/backend/src/controllers/UserController.ts@@ -16,7 +16,7 @@ export class UserController {const theUserName = configService.config.USER_NAME;- if (username === theUserName && password === configService.config.USER_PASSWORD) {+ if (username === theUserName && configService.verifyPassword(password)) {// Express way of setting cookiesconst sessionDuration = configService.config.SESSION_DURATION || 7;const token = jwt.sign({ user: theUserName }, configService.config.SECRET, {diff --git a/backend/src/services/ConfigService.ts b/backend/src/services/ConfigService.tsindex b272c97..c02c4d2 100644--- a/backend/src/services/ConfigService.ts+++ b/backend/src/services/ConfigService.ts@@ -1,10 +1,13 @@import { z } from 'zod';import fs from 'fs';import crypto from 'crypto';+import bcrypt from 'bcryptjs';import { appPaths } from '../utils/AppPaths';import path from 'path';import { requiresKeyringSetup } from '../utils/installHelpers';+const BCRYPT_SALT_ROUNDS = 10;+// Schema for the .env config file (with optional sensitive fields for setup mode)const baseConfigSchema = z.object({// General@@ -68,12 +71,14 @@ const userConfigSchema = baseConfigSchemaconst finalConfigSchema = configSchema.extend({SECRET: z.string().min(12),APIKEY: z.string().min(12),+ PASSWORD_HASH: z.string().min(1).optional(),});// Setup mode config schema (doesn't require sensitive fields)const setupModeConfigSchema = baseConfigSchema.extend({SECRET: z.string().min(12),APIKEY: z.string().min(12),+ PASSWORD_HASH: z.string().min(1).optional(),SETUP_PENDING: z.literal(true),});@@ -164,17 +169,21 @@ class ConfigService {this.keysPath = path.join(appPaths.getDataDir(), 'keys.json');const secrets = this.loadOrGenerateSecrets(envConfig.SECRET, envConfig.APIKEY);- // 4. Merge all sources (file overrides env, which overrides defaults)+ // 4. Hash the password if provided via env var+ const passwordHash = this.hashPasswordIfNeeded(envConfig.USER_PASSWORD);++ // 5. Merge all sources (file overrides env, which overrides defaults)const mergedConfig = {...envConfig,...fileConfig,SECRET: secrets.SECRET, // System secrets fill in the gapsAPIKEY: secrets.APIKEY,+ PASSWORD_HASH: passwordHash,IS_DOCKER: rawEnv.IS_DOCKER === 'true' || rawEnv.IS_DOCKER === '1',IS_BINARY: (process as any).pkg ? true : false,};- // 5. Validate final configuration+ // 6. Validate final configurationconst parsedConfig = finalConfigSchema.safeParse(mergedConfig);if (!parsedConfig.success) {@@ -192,6 +201,7 @@ class ConfigService {ENCRYPTION_KEY: '', // Will be set during setupUSER_NAME: 'admin', // Default valueUSER_PASSWORD: '', // Will be set during setup+ PASSWORD_HASH: '', // Will be set during setupSETUP_PENDING: true,} as SetupModeConfig;@@ -259,9 +269,84 @@ class ConfigService {return { SECRET: finalSecret, APIKEY: finalApiKey };}+ /**+ * Hash a plaintext password and store the hash in keys.json.+ * If no plaintext password is provided, returns the existing hash from keys.json (if any).+ */+ private hashPasswordIfNeeded(plaintextPassword?: string): string | undefined {+ let keysFileContent: Record<string, any> = {};+ try {+ if (fs.existsSync(this.keysPath)) {+ keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));+ }+ } catch (error) {+ // Ignore read errors+ }++ // If a plaintext password is provided (from env var), hash it and store+ if (plaintextPassword) {+ const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);+ try {+ const newContent = { ...keysFileContent, PASSWORD_HASH: hash };+ const dir = path.dirname(this.keysPath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });+ console.log('[ConfigService] Password hash stored in keys.json');+ } catch (error) {+ console.error(`[ConfigService] Failed to save password hash to keys.json: ${error}`);+ }+ return hash;+ }++ // Otherwise, return the existing hash from keys.json (for keyring/setup flow)+ return keysFileContent.PASSWORD_HASH || undefined;+ }++ /**+ * Hash a password and store the hash in keys.json.+ * Used by SetupController and password change endpoints.+ */+ public hashAndStorePassword(plaintextPassword: string): string {+ const hash = bcrypt.hashSync(plaintextPassword, BCRYPT_SALT_ROUNDS);++ let keysFileContent: Record<string, any> = {};+ try {+ if (fs.existsSync(this.keysPath)) {+ keysFileContent = JSON.parse(fs.readFileSync(this.keysPath, 'utf-8'));+ }+ } catch (error) {+ // Ignore read errors+ }++ try {+ const newContent = { ...keysFileContent, PASSWORD_HASH: hash };+ const dir = path.dirname(this.keysPath);+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(this.keysPath, JSON.stringify(newContent, null, 2), { mode: 0o600 });+ console.log('[ConfigService] Password hash updated in keys.json');+ } catch (error) {+ console.error(`[ConfigService] Failed to save password hash to keys.json: ${error}`);+ }++ // Update in-memory config+ (this._config as any).PASSWORD_HASH = hash;++ return hash;+ }++ /**+ * Verify a plaintext password against the stored bcrypt hash.+ */+ public verifyPassword(plaintextPassword: string): boolean {+ const hash = (this._config as any).PASSWORD_HASH;+ if (!hash) return false;+ return bcrypt.compareSync(plaintextPassword, hash);+ }+/*** Gets the singleton instance of the ConfigService.*/+public static getInstance(): ConfigService {if (!ConfigService.instance) {ConfigService.instance = new ConfigService();@@ -289,10 +374,14 @@ class ConfigService {throw new Error('Setup is not pending. Cannot complete setup.');}+ // Hash the password and store in keys.json+ const passwordHash = this.hashAndStorePassword(credentials.USER_PASSWORD);+// Update the config with the new credentialsthis._config = {...this._config,...credentials,+ PASSWORD_HASH: passwordHash,SETUP_PENDING: false,} as AppConfig;@@ -315,6 +404,7 @@ class ConfigService {const credentials = await keyringService.getAllCredentials();if (credentials.ENCRYPTION_KEY && credentials.USER_NAME && credentials.USER_PASSWORD) {+ // All credentials present - complete normal setupConfigService.instance.completeSetup({ENCRYPTION_KEY: credentials.ENCRYPTION_KEY,USER_NAME: credentials.USER_NAME,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 146e9a3..3a9b33a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -41,6 +41,9 @@ importers:'@napi-rs/keyring':specifier: ^1.2.0version: 1.2.0+ bcryptjs:+ specifier: ^3.0.3+ version: 3.0.3better-sqlite3:specifier: 12.2.0version: 12.2.0@@ -2954,6 +2957,10 @@ packages:resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==}+ resolution: {integrity: sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==}+ hasBin: true+resolution: {integrity: sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==}@@ -9663,6 +9670,8 @@ snapshots:dependencies:tweetnacl: 0.14.5+ [email protected]: {}+